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

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

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

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


当前回答

嗯,我们可以得到元素几何…

var geometry;
geometry={};
var element=document.getElementById(#ibims);
var rect = element.getBoundingClientRect();
this.geometry.top=rect.top;
this.geometry.right=rect.right;
this.geometry.bottom=rect.bottom;
this.geometry.left=rect.left;
this.geometry.height=this.geometry.bottom-this.geometry.top;
this.geometry.width=this.geometry.right-this.geometry.left;
console.log(this.geometry);

这个纯JS怎么样?

其他回答

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

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

罗马,档案。

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

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

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

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

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

它应该只是

$('#someDiv').height();

与jQuery。这将以数字的形式检索换行集中第一项的高度。

尝试使用

.style.height

只有在您首先设置了该属性时才有效。不是很有用!

有时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;
}