无法通过JavaScript获取元素高度以将元素定位到中心

问题描述 投票:0回答:1

我正在尝试使用 JavaScript 将跨度置于段落内的中心。这是我的代码:

document.addEventListener('DOMContentLoaded', () =>  {
    window.onload = function(){middle();}
    var titleHeight = document.getElementById("page-title").clientHeight;
    var titleWidth = document.getElementById("page-title").clientWidth;
    var objHeight = document.getElementById("head-text").clientHeight;
    var objWidth = document.getElementById("head-text").clientHeight;
    var moveit = document.getElementById("head-text");
    var moveit = document.getElementById("head-text");
    function middle(){
        console.log(titleHeight/2-objHeight/2);
        moveit.style.top=titleHeight/2-objHeight/2;
        moveit.style.left=titleWidth/2-objWidth/2);
        }
})

它总是返回未定义的titleHeight。我该如何解决这个问题?

我尝试通过 css 将元素居中,但这没有帮助。所以我不得不切换到 JavaScript。我需要任何可能的方式通过 JavaScript 来定位我的元素。

javascript html positioning
1个回答
0
投票

你确实应该使用 CSS 来做到这一点,但在 JS 中你需要调用

element.getBoundingClientRect()
来获取准确的位置信息。

此外,您将

objWidth
设置为
clientHeight

它很慢并且会导致卡顿,但是...

document.addEventListener('DOMContentLoaded', () =>  {
    window.onload = function(){middle();}


    function middle(){
        // This can change, so needs to be in the `middle` function
        const title = document.getElementById("page-title").getBoundingClientRect();
        const titleHeight = title.height;
        const titleWidth = title.width;

        const moveit = document.getElementById("head-text");
        const head = moveit.getBoundingClientRect();
        const objHeight = title.height;
        const objWidth = title.width; // fix typo

        console.log(titleHeight/2-objHeight/2);

        moveit.style.top=titleHeight/2-objHeight/2;
        moveit.style.left=titleWidth/2-objWidth/2);
    }
})
© www.soinside.com 2019 - 2024. All rights reserved.