javascript 在添加到 DOM 之前获取元素的高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5944038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 18:53:24  来源:igfitidea点击:

Getting the height of an element before added to the DOM

javascriptdomheightappendelement

提问by Ruffy

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.

*注意:这只是我正在处理的功能的简化版本,以便在没有所有不必要的混乱的情况下投射我想要实现的目标。

回答by Ben Blank

Elements don't havea 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: hiddenso that the element can be added to the DOM (and its height determined) without causing visible flickering. (jsFiddle)

您可以很容易地使用visibility: hidden它来解决这个问题,这样可以将元素添加到 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 topbecause 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 中的空间(因此它们的尺寸必须计算),但实际上不能被用户看到。

回答by vsync

Here is a working demo of how to measure an element by brieflyadding it to the DOM and inspecting its height, then removing it. This method might be costly since the node is cloned, so the added styles won't affect it afterwards and all DOM eventswill be removed from it.

这是一个如何通过简单地将元素添加到 DOM 并检查其高度,然后将其删除来测量元素的工作演示。由于节点是克隆的,因此此方法可能成本很高,因此添加的样式之后不会影响它,并且所有DOM 事件都将从中删除。

If the inspected node has a lot of sub-nodes, this might not be efficient, but stil can be quite handy.

如果被检查的节点有很多子节点,这可能效率不高,但仍然非常方便。

function getNodeHeight(node) {
    var height, clone = node.cloneNode(true)
    // hide the meassured (cloned) element
    clone.style.cssText = "position:fixed; top:-9999px; opacity:0;"
    // add the clone to the DOM 
    document.body.appendChild(clone)
    // meassure it
    height = clone.clientHeight
    // cleaup 
    clone.parentNode.removeChild(clone)
    return height
}


var newDiv = document.createElement("div");
newDiv.innerHTML = `Lorem ipsum dolor sit amet, consectetur adipiscing elit, 
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 

<h1>deserunt mollit anim id est laborum.<h1>`


// print the height of "newDiv"
console.log( getNodeHeight(newDiv) )