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 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?
在将元素附加到DOM之前,有没有办法获得元素的高度?我知道clientHeight不能正常工作,它总是返回0.是否有其他方法可以返回高度或元素是否必须是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.
*注意:这只是我正在处理的函数的简化版本,以便在没有所有不需要的混乱的情况下投影我想要实现的功能。
1 个解决方案
#1
32
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. (jsFiddle)
您可以使用可见性轻松地解决这个问题:隐藏,以便可以将元素添加到DOM(及其高度确定),而不会导致可见的闪烁。 (的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中的空间(所以必须计算它们的大小),但实际上用户无法看到它们。
#1
32
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. (jsFiddle)
您可以使用可见性轻松地解决这个问题:隐藏,以便可以将元素添加到DOM(及其高度确定),而不会导致可见的闪烁。 (的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中的空间(所以必须计算它们的大小),但实际上用户无法看到它们。