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中的空间(因此必须计算其大小),但实际上无法被用户看到。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…