如何获得div的内容高度

时间:2013-03-11 21:06:51

标签: javascript jquery css

我的div有一个样式position:absolute,因此,如果内容高于它的高度,它就不会展开。

因此,我认为如果我找到实际内容的高度是一个解决方案,并使用div样式为position:absolute指定高度。

知道怎么做吗?或者想知道如何让absolute div根据其内容进行扩展。

提前致谢!

8 个答案:

答案 0 :(得分:1)

这是获得容器高度的可怕方法。我们基本上克隆整个div,设置位置使其具有高度,检查高度,然后将其删除:

$(function () {
    var clone = null;
    alert( clone = $('.test').clone().css('position', 'static').appendTo(".container").height());
    clone.remove();
});

这是小提琴:http://jsfiddle.net/vPMDh/1/

答案 1 :(得分:1)

Element.scrollHeight应该完成这项工作。

答案 2 :(得分:0)

即使是绝对的,也应该扩大。 检查你没有身高:xxpx

如果是,请将其更改为min-height

答案 3 :(得分:0)

使用clearfix hack。 heres the link

并向你的div添加clearfix

例如

样式表中的

<style>
.clearfix:after {
    content: ".";
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
}

.clearfix {
    display: inline-block;
}

html[xmlns] .clearfix {
    display: block;
}

* html .clearfix {
    height: 1%;
}
</style>

... 并在你的div中添加 clearfix

<div class="clearfix">
   //some html tags
</div>

答案 4 :(得分:0)

正如你所说的那样"it doesn't expand if the content is higher than it's height."我猜你有一个固定的高度设置..如果你出于某种原因确实需要它,请尝试使用min-height

看看这个fiddle

答案 5 :(得分:0)

<div class="classname">

Some content....


<p style="clear:both">&nbsp</p>
</div>

答案 6 :(得分:0)

感谢您提出问题。如果您使用此:

$(document).ready(function(){

 var x = $("#container").height();
 alert(x);

//if not works then 
  var y = $("#container").outerHeight();
  alert(y);

});

如果你不应用div的高度,我认为找到任何div的高度很简单。

答案 7 :(得分:0)

与@MattDiamant类似的解决方案,但是使用vanilla JS并且没有创建克隆:

function getDivHeight(posAbsoluteDiv) {
   const heightBackup = posAbsoluteDiv.style.height;

   posAbsoluteDiv.style.height = 'auto';

   const contentHeight = posAbsoluteDiv.getBoundingClientRect().height;

   posAbsoluteDiv.style.height = heightBackup;

   return contentHeight;
}
相关问题