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

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

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

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


当前回答

它应该只是

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

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

尝试使用

.style.height

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

其他回答

我用它来获取一个元素的高度(返回浮点数):

document.getElementById('someDiv').getBoundingClientRect().height

当您使用虚拟DOM时,它也可以工作。我在Vue中这样使用它:

this.$refs['some-ref'].getBoundingClientRect().height

对于Vue组件:

this.$refs['some-ref'].$el.getBoundingClientRect().height

offsetHeight,通常。

如果你需要计算一些东西,但不显示它,将元素设置为visibility:hidden和position:absolute,将它添加到DOM树,获取offsetHeight,然后删除它。(这就是上次我检查的原型库在幕后所做的工作)。

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

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

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

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

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