如何获得元素的渲染高度?
假设你有一个<div>元素,里面有一些内容。里面的内容将扩展<div>的高度。当你没有显式地设置高度时,你如何获得“渲染”的高度。显然,我尝试过:
var h = document.getElementById('someDiv').style.height;
这样做有什么诀窍吗?如果有帮助的话,我正在使用jQuery。
如何获得元素的渲染高度?
假设你有一个<div>元素,里面有一些内容。里面的内容将扩展<div>的高度。当你没有显式地设置高度时,你如何获得“渲染”的高度。显然,我尝试过:
var h = document.getElementById('someDiv').style.height;
这样做有什么诀窍吗?如果有帮助的话,我正在使用jQuery。
当前回答
有时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;
}
其他回答
我做了一个简单的代码,甚至不需要JQuery,可能会帮助一些人。 它在加载后得到ID1的总高度并在ID2上使用它
function anyName(){
var varname=document.getElementById('ID1').offsetHeight;
document.getElementById('ID2').style.height=varname+'px';
}
然后设置主体来加载它
<body onload='anyName()'>
style = window.getComputedStyle(your_element);
然后简单地: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;
}
你在css中设置高度了吗?如果你没有,你需要使用offsetHeight;而不是身高
var h = document.getElementById('someDiv').style.offsetHeight;
我用它来获取一个元素的高度(返回浮点数):
document.getElementById('someDiv').getBoundingClientRect().height
当您使用虚拟DOM时,它也可以工作。我在Vue中这样使用它:
this.$refs['some-ref'].getBoundingClientRect().height
对于Vue组件:
this.$refs['some-ref'].$el.getBoundingClientRect().height