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

假设你有一个<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;
}

其他回答

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

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怎么样?

如果我正确理解了你的问题,那么也许这样做会有所帮助:

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');
    } 
}

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

MooTools:

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

为此,您可以使用. 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()之间的差异