如何获得元素的渲染高度?
假设你有一个<div>元素,里面有一些内容。里面的内容将扩展<div>的高度。当你没有显式地设置高度时,你如何获得“渲染”的高度。显然,我尝试过:
var h = document.getElementById('someDiv').style.height;
这样做有什么诀窍吗?如果有帮助的话,我正在使用jQuery。
如何获得元素的渲染高度?
假设你有一个<div>元素,里面有一些内容。里面的内容将扩展<div>的高度。当你没有显式地设置高度时,你如何获得“渲染”的高度。显然,我尝试过:
var h = document.getElementById('someDiv').style.height;
这样做有什么诀窍吗?如果有帮助的话,我正在使用jQuery。
当前回答
我做了一个简单的代码,甚至不需要JQuery,可能会帮助一些人。 它在加载后得到ID1的总高度并在ID2上使用它
function anyName(){
var varname=document.getElementById('ID1').offsetHeight;
document.getElementById('ID2').style.height=varname+'px';
}
然后设置主体来加载它
<body onload='anyName()'>
其他回答
试一试:
var h = document.getElementById('someDiv').clientHeight;
var h = document.getElementById('someDiv').offsetHeight;
var h = document.getElementById('someDiv').scrollHeight;
clientHeight包括高度和垂直填充。
offsetHeight包括高度、垂直填充和垂直边框。
scrollHeight包括所包含文档的高度(在滚动的情况下会大于高度)、垂直填充和垂直边框。
如果我正确理解了你的问题,那么也许这样做会有所帮助:
function testDistance(node1, node2) {
/* get top position of node 1 */
let n1Pos = node1.offsetTop;
/* get height of node 1 */
let n1Height = node1.clientHeight;
/* get top position of node 2 */
let n2Pos = node2.offsetTop;
/* get height of node 2 */
let n2Height = node2.clientHeight;
/* add height of both nodes */
let heightTogether = n1Height + n2Height;
/* calculate distance from top of node 1 to bottom of node 2 */
let actualDistance = (n2Pos + n2Height) - n1Pos;
/* if the distance between top of node 1 and bottom of node 2
is bigger than their heights combined, than there is something between them */
if (actualDistance > heightTogether) {
/* do something here if they are not together */
console.log('they are not together');
} else {
/* do something here if they are together */
console.log('together');
}
}
它应该只是
$('#someDiv').height();
与jQuery。这将以数字的形式检索换行集中第一项的高度。
尝试使用
.style.height
只有在您首先设置了该属性时才有效。不是很有用!
如果你已经在使用jQuery,你最好的选择是. outerheight()或.height(),如上所述。
没有jQuery,你可以检查使用的box-sizing和添加各种填充+边框+ clientHeight,或者你可以使用getComputedStyle:
罗马,档案。
H现在是一个字符串,比如" 538.25 px"。
我找不到引用,但我听说getComputedStyle()很昂贵,所以它可能不是你想在每个窗口调用的东西。onscroll事件(但是,也不是jQuery的height())。
document.querySelector('.project_list_div').offsetHeight;