如何获得元素的渲染高度?

假设你有一个<div>元素,里面有一些内容。里面的内容将扩展<div>的高度。当你没有显式地设置高度时,你如何获得“渲染”的高度。显然,我尝试过:

var h = document.getElementById('someDiv').style.height;

这样做有什么诀窍吗?如果有帮助的话,我正在使用jQuery。


当前回答

非JQUERY,因为有一堆链接使用element .style.height在这些答案的顶部…

内部高度: https://developer.mozilla.org/en-US/docs/Web/API/Element.clientHeight

document.getElementById(id_attribute_value).clientHeight;

外高度: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.offsetHeight

document.getElementById(id_attribute_value).offsetHeight; 

或者是我最喜欢的参考资料之一:http://youmightnotneedjquery.com/

其他回答

一定使用

$('#someDiv').height()   // to read it

or

$('#someDiv').height(newHeight)  // to set it

我把这个作为一个额外的答案,因为我刚刚学到一些重要的东西。

我差点掉进了刚才使用offsetHeight的陷阱。事情是这样的:

我使用了使用调试器的老技巧来“观察”我的元素具有哪些属性 我看到了哪个值在我期望的值附近 它是offsetHeight,所以我用了它。 然后我意识到它不工作与隐藏DIV 我试着在计算maxHeight后隐藏,但看起来笨拙-弄得一团糟。 我搜索了一下——发现了jQuery.height()——并使用了它 发现height()甚至适用于隐藏元素 只是为了好玩,我检查了高度/宽度的jQuery实现

以下只是其中的一部分:

Math.max(
Math.max(document.body["scroll" + name], document.documentElement["scroll" + name]),
Math.max(document.body["offset" + name], document.documentElement["offset" + name])
) 

是的,它既看滚动和偏移。如果失败了,考虑到浏览器和css兼容性问题,它会进一步考虑。换句话说,那些我不关心或者不想关心的东西。

但我不需要。由于jQuery !

这个故事的寓意是:如果jQuery为某件事提供了一个方法,那么它可能有一个很好的理由,很可能与兼容性有关。

如果你最近还没有通读jQuery的方法列表,我建议你看一看。

document.querySelector('.project_list_div').offsetHeight;

有时offsetHeight会返回0,因为您创建的元素还没有在Dom中呈现。在这种情况下,我写了这个函数:

function getHeight(element)
{
    var e = element.cloneNode(true);
    e.style.visibility = "hidden";
    document.body.appendChild(e);
    var height = e.offsetHeight + 0;
    document.body.removeChild(e);
    e.style.visibility = "visible";
    return height;
}
style = window.getComputedStyle(your_element);

然后简单地:style.height

你在css中设置高度了吗?如果你没有,你需要使用offsetHeight;而不是身高

var h = document.getElementById('someDiv').style.offsetHeight;