3

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

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

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

提前致谢!

4

8 回答 8

3

Element.scrollHeight应该做的工作。

于 2013-07-15T21:20:21.727 回答
1

这是获取容器高度的一种糟糕方法。我们基本上是在克隆整个 div,设置位置使其具有高度,检查该高度,然后将其删除:

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

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

于 2013-03-11T21:40:12.183 回答
0

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

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

于 2013-03-11T21:09:41.940 回答
0

使用 clearfix hack。这是链接

并将 clearfix 添加到您的 div

例子

在您的样式表中

<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>
于 2013-03-11T21:10:39.160 回答
0

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

看看这个小提琴

于 2013-03-11T21:19:00.123 回答
0
<div class="classname">

Some content....


<p style="clear:both">&nbsp</p>
</div>
于 2013-03-11T21:29:40.393 回答
0

感谢您提出您的问题。如果你使用这个:

$(document).ready(function(){

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

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

});

我认为如果你不应用 div 的高度,那么很容易找到任何 div 的高度。

于 2013-03-11T22:00:20.813 回答
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;
}
于 2017-09-13T17:19:12.863 回答