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

问题描述 投票:337回答:17

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

假设你有一个<div>元素,里面有一些内容。里面的这个内容将拉伸<div>的高度。如果没有明确设置高度,如何获得“渲染”高度。显然,我试过:

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

这样做有诀窍吗?如果有帮助我正在使用jQuery。

javascript jquery css height
17个回答
160
投票

它应该是

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

用jQuery。这将检索包装集中第一个项目的高度作为数字。

试着用

.style.height

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


8
投票

嗯,我们可以获得Element几何...

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


6
投票

offsetHeight,通常。

如果您需要计算某些内容但未显示它,请将该元素设置为visibility:hiddenposition:absolute,将其添加到DOM树中,获取offsetHeight,然后将其删除。 (这就是我上次检查时原型库在幕后所做的事情)。


5
投票

有时offsetHeight将返回零,因为您创建的元素尚未在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;
}

4
投票

如果你已经使用jQuery,你最好的选择是.outerHeight().height(),如前所述。

没有jQuery,你可以检查使用中的框大小并添加各种填充+边框+ clientHeight,或者你可以使用getComputedStyle

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

h现在将是一个像“53.825px”的字符串。

我找不到参考,但我想我听说getComputedStyle()可能很贵,所以它可能不是你想在每个window.onscroll事件上调用的东西(但是,然后,jQuery的height()也不是)。


2
投票

使用MooTools:

$( 'someDiv')。的getSize()。ÿ


1
投票
document.querySelector('.project_list_div').offsetWidth;

1
投票

如果我理解你的问题,那么这样的事情可能会有所帮助:

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

-4
投票

你有具体设置css的高度吗?如果你还没有,你需要使用offsetHeight;而不是height

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

1065
投票

尝试以下之一:

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

clientHeight包括高度和垂直填充。

offsetHeight包括高度,垂直填充和垂直边框。

scrollHeight包含所包含文档的高度(在滚动的情况下将大于高度),垂直填充和垂直边框。


137
投票

NON JQUERY,因为在这些答案的顶部有一些使用elem.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/


44
投票

你可以使用.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的网站或detailed post here

它将清除.height() / innerHeight() / outerHeight()之间的区别


27
投票
style = window.getComputedStyle(your_element);

然后简单地说:style.height


18
投票

我用这个:

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

它在您使用虚拟DOM时也有效。我在Vue中使用它像这样:

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

15
投票

绝对使用

$('#someDiv').height()   // to read it

要么

$('#someDiv').height(newHeight)  // to set it

我发布这个作为额外的答案,因为我刚刚学到了几件重要的事情。

我刚刚使用offsetHeight陷入陷阱。这就是发生的事情:

  • 我使用了一个很好的老技巧,使用调试器来“监视”我的元素具有哪些属性
  • 我看到哪一个值具有我期望的值
  • 它偏移了 - 所以我用了它。
  • 然后我意识到它与隐藏的DIV无法合作
  • 我在计算maxHeight之后试图隐藏但看起来很笨拙 - 弄得一团糟。
  • 我做了一个搜索 - 发现了jQuery.height() - 并使用了它
  • 发现height()甚至可以在隐藏元素上运行
  • 只是为了好玩,我检查了高度/宽度的jQuery实现

这只是其中的一部分:

Math.max(
Math.max(document.body["scroll" + name], document.documentElement["scroll" + name]),
Math.max(document.body["offset" + name], document.documentElement["offset" + name])
) 

是的,它看着两个滚动和偏移。如果失败,它会更进一步,考虑到浏览器和CSS兼容性问题。换句话说,我不关心 - 或者想要。

但我没有。谢谢jQuery!

故事的道德:如果jQuery有一个方法可能有一个很好的理由,可能与兼容性有关。

如果你最近没有读过jQuery list of methods,我建议你看看。


12
投票

我做了一个简单的代码,甚至不需要JQuery,可能会帮助一些人。它在加载后获得'ID1'的总高度并在'ID2'上使用它

function anyName(){
    var varname=document.getElementById('ID1').offsetHeight;
    document.getElementById('ID2').style.height=varname+'px';
}

然后只需将主体设置为加载它

<body onload='anyName()'>

8
投票

这是答案吗?

“如果你需要计算一些但不显示它,将元素设置为visibility:hiddenposition:absolute,将它添加到DOM树中,获取offsetHeight,然后将其删除。(这就是我上次检查时原型库背后的行) “。

我对许多元素都有同样的问题。网站上没有jQuery或Prototype,但我赞成借用这项技术。作为一些无法工作的事情的例子,接着是做了什么,我有以下代码:

// Layout Height Get
function fnElementHeightMaxGet(DoScroll, DoBase, elementPassed, elementHeightDefault)
{
    var DoOffset = true;
    if (!elementPassed) { return 0; }
    if (!elementPassed.style) { return 0; }
    var thisHeight = 0;
    var heightBase = parseInt(elementPassed.style.height);
    var heightOffset = parseInt(elementPassed.offsetHeight);
    var heightScroll = parseInt(elementPassed.scrollHeight);
    var heightClient = parseInt(elementPassed.clientHeight);
    var heightNode = 0;
    var heightRects = 0;
    //
    if (DoBase) {
        if (heightBase > thisHeight) { thisHeight = heightBase; }
    }
    if (DoOffset) {
        if (heightOffset > thisHeight) { thisHeight = heightOffset; }
    }
    if (DoScroll) {
        if (heightScroll > thisHeight) { thisHeight = heightScroll; }
    }
    //
    if (thisHeight == 0) { thisHeight = heightClient; }
    //
    if (thisHeight == 0) { 
        // Dom Add:
        // all else failed so use the protype approach...
        var elBodyTempContainer = document.getElementById('BodyTempContainer');
        elBodyTempContainer.appendChild(elementPassed);
        heightNode = elBodyTempContainer.childNodes[0].offsetHeight;
        elBodyTempContainer.removeChild(elementPassed);
        if (heightNode > thisHeight) { thisHeight = heightNode; }
        //
        // Bounding Rect:
        // Or this approach...
        var clientRects = elementPassed.getClientRects();
        heightRects = clientRects.height;
        if (heightRects > thisHeight) { thisHeight = heightRects; }
    }
    //
    // Default height not appropriate here
    // if (thisHeight == 0) { thisHeight = elementHeightDefault; }
    if (thisHeight > 3000) {
        // ERROR
        thisHeight = 3000;
    }
    return thisHeight;
}

这基本上只是为了获得零结果而尝试任何东西。 ClientHeight没有任何影响。对于问题元素,我通常在Base中获得NaN,在Offset和Scroll高度中获得零。然后我尝试了添加DOM解决方案和clientRects以查看它是否在这里工作。

2011年6月29日,我确实更新了代码,尝试添加DOM和clientHeight,结果比我预期的更好。

1)clientHeight也是0。

2)Dom实际上给了我一个很棒的高度。

3)ClientRects返回与DOM技术几乎相同的结果。

因为添加的元素本质上是流体,当它们被添加到其他空的DOM Temp元素时,它们将根据该容器的宽度进行渲染。这很奇怪,因为它比最终结束时短30px。

我添加了一些快照来说明高度的计算方式不同。

高度差异很明显。我当然可以添加绝对定位和隐藏,但我相信这将无效。我继续相信这不会奏效!

(我进一步讨论)高度出现(渲染)低于真实的渲染高度。这可以通过设置DOM Temp元素的宽度以匹配现有父元素来解决,并且理论上可以相当准确地完成。我也不知道删除它们并将它们添加回现有位置会导致什么结果。当他们通过innerHTML技术到达时,我将使用这种不同的方法。

*但是*这些都不是必需的。事实上,它像广告一样工作,并返回正确的高度!

当我能够再次看到菜单时,DOM已经根据页面顶部的流体布局返回了正确的高度(279px)。上面的代码也使用了返回280px的getClientRects。

这在以下快照中说明(一旦工作,从Chrome中获取。)

现在我不知道为什么原型技巧有效,但似乎。或者,getClientRects也可以。

我怀疑这些特定元素的所有问题的原因是使用innerHTML而不是appendChild,但这是纯粹的猜测。

© www.soinside.com 2019 - 2024. All rights reserved.