Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

javascript - 在添加到DOM之前获取元素的高度(Getting the height of an element before added to the DOM)

Is there any way to get an element's height prior to appending it to the DOM?

(在将元素附加到DOM之前,有什么方法可以获取它的高度?)

I know that clientHeight doesn't work as I've tried and it always returns 0. Are there other methods that may return the height or does the element have to be a part of the DOM in order for the height to be calculated?

(我知道clientHeight无法正常工作,并且总是返回0。是否有其他方法可以返回height,或者元素必须是DOM的一部分才能计算高度?)

This is a sample of what I'm going for:

(这是我想要的示例:)

function test(a) {
    var a=document.createElement(a)
    a.style.top=(window.innerHeight/2-a.clientHeight/2)+'px' //fixed position in CSS
    document.body.appendChild(a)
    }

*Note: This is only a simplified version of the function I'm working on in order to project what I'm trying to achieve without all of the unneeded mess.

(*注意:这只是我正在使用的功能的简化版本,目的是在没有所有不必要的混乱的情况下投影出我要实现的目标。)

  ask by Ruffy translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

(元素不具备的高度,在任何真正意义上的,直到他们已经被添加到DOM,因为他们的风格不能在那之前进行评估。)

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.

(您可以使用visibility: hidden轻松地解决此问题visibility: hidden以便可以将元素添加到DOM(并确定其高度)而不会引起可见的闪烁。)

( jsFiddle )

(( 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.

((这是在假设您使用top的前提下进行的,因为该元素是绝对定位或固定的。如果不是,则需要暂时??使它固定。)隐藏的元素仍会占用DOM中的空间(因此必须计算其大小),但实际上无法被用户看到。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...