Getting the height of an element before added to the DOM

后端 未结 2 1605
别跟我提以往
别跟我提以往 2020-12-17 07:51

Is there any way to get an element\'s height prior to appending it to the DOM? I know that clientHeight doesn\'t work as I\'ve tried and it always returns 0. Are there other

2条回答
  •  既然无缘
    2020-12-17 08:33

    Elements don't have a height, in any real sense, until they've been added to the DOM, as their styles cannot be evaluated until then.

    You can get around this easily enough using visibility: hidden so that the element can be added to the DOM (and its height determined) without causing visible flickering. (jsFiddle)

    function test(a) {
        var a=document.createElement(a);
        a.style.visibility = "hidden";
        document.body.appendChild(a);
        a.style.top=(window.innerHeight/2-a.clientHeight/2)+'px';
        a.style.visibility = "";
    }
    

    (This is working on the assumption that you're using top because the element is absolutely positioned or fixed. If it weren't, you'd need to make it so temporarily.) Hidden elements still take up space in the DOM (so their sizes must be calculated), but cannot actually be seen by the user.

提交回复
热议问题