如何测量没有高度的div的高度

时间:2013-09-30 12:02:57

标签: jquery html css

我需要获得div的高度。我无法在css中设置高度,因为内容可能会发生变化(取决于其中的内容)。 我试过了:

var buttonsHeight = $(".buttonsContainer").height();

var buttonsHeight = $(".buttonsContainer").outerHeight();

var buttonsHeight = $(".buttonsContainer").innerHeight();

在每种情况下,buttonsHeight都是null

CSS:

.buttonsContainer{
  padding:31px 16px 0;
  position:fixed;
}

小提琴: http://jsfiddle.net/U7Kck/3/

如果你更换 填充:20px 0;高度:40px然后buttonsContainer看起来很好......

5 个答案:

答案 0 :(得分:0)

var buttonsHeight = $(".buttonsContainer")[0].clientHeight

答案 1 :(得分:0)

我认为当页面打开时,它给div的高度,我现在无法测试,但我想你可以得到它:

$(".buttonsContainer").css("height")

答案 2 :(得分:0)

试试这个:

var elem = $('.buttonsContainer')[0];
buttonsHeight = window.getComputedStyle(elem, null).getPropertyValue('height');

getComputedStyle的文档可用here

答案 3 :(得分:0)

这些jQuery方法运行正常。 例如:

$(document).ready(function() {
    var buttonsHeight = $(".buttonsContainer").height();
   console.log("height: " + buttonsHeight);
    buttonsHeight = $(".buttonsContainer").innerHeight();
   console.log("inner height: " + buttonsHeight);
    buttonsHeight = $(".buttonsContainer").outerHeight();
   console.log("outer height: " + buttonsHeight);
});

使用简单的HTML,如:

<div class="buttonsContainer">Some <br/>content</div>
<div class="buttonsContainer">Some content</div>

即使有多个buttonsContainer元素,它也能正常工作。只返回找到的第一个元素的高度。

http://jsfiddle.net/KBR3r/2/

所以我猜问题就在别的地方。

答案 4 :(得分:0)

clientHeightoffsetHeight为您完成工作。在这里检查他们是否正常工作。根据您的要求使用上述任何一项,无论您是否考虑边框宽度。 http://jsfiddle.net/KzTDS/。要更好地了解offsetHeightclientHeight,请查看此difference between offsetHeight and clientHeight

以下是如何使用

 document.getElementById('button').clientHeight; // Same as below but does not include border scrollbar and no margin
 document.getElementById('button').offsetHeight; // content, padding, border, scrollbar and no margin