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

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

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

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


当前回答

为此,您可以使用. outerheight()。

它会给你元素的完整渲染高度。此外,您不需要设置元素的css-height。为预防起见,你可以保持它的高度自动,这样它就可以根据内容的高度来渲染。

//if you need height of div excluding margin/padding/border
$('#someDiv').height();

//if you need height of div with padding but without border + margin
$('#someDiv').innerHeight();

// if you need height of div including padding and border
$('#someDiv').outerHeight();

//and at last for including border + margin + padding, can use
$('#someDiv').outerHeight(true);

想要更清楚地了解这些函数,你可以访问jQuery的网站或这里的详细文章。

它将清除.height() / innerHeight() / outerHeight()之间的差异

其他回答

MooTools:

$ (' someDiv ') .getSize .y ()

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

如果你已经在使用jQuery,你最好的选择是. outerheight()或.height(),如上所述。

没有jQuery,你可以检查使用的box-sizing和添加各种填充+边框+ clientHeight,或者你可以使用getComputedStyle:

罗马,档案。

H现在是一个字符串,比如" 538.25 px"。

我找不到引用,但我听说getComputedStyle()很昂贵,所以它可能不是你想在每个窗口调用的东西。onscroll事件(但是,也不是jQuery的height())。

style = window.getComputedStyle(your_element);

然后简单地:style.height

非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/