[英]How to get div's content height
My div has a styling position:absolute
, and as a result, it doesn't expand if the content is higher than it's height. 我的div有一个造型
position:absolute
,因此,如果内容高于它的高度,它不会扩展。
Therefore, I thought that a solution would be if I find what the is the actual content's height, and assign the height to the div
with the position:absolute
styling. 因此,我认为如果我找到实际内容的高度是一个解决方案,并使用
position:absolute
styling将高度分配给div
。
Any idea how to do it? 知道怎么做吗? or maybe an idea how to make an
absolute
div
to expand according to its content. 或者可能是一个想法如何根据其内容使
absolute
div
扩展。
Thanks in advance! 提前致谢!
Here's an awful way to get the height of the container. 这是获得容器高度的可怕方法。 We're basically cloning the whole div, setting the position so that it has height, checking that height, and then removing it:
我们基本上克隆整个div,设置位置使其具有高度,检查高度,然后将其移除:
$(function () {
var clone = null;
alert( clone = $('.test').clone().css('position', 'static').appendTo(".container").height());
clone.remove();
});
Here's the fiddle: http://jsfiddle.net/vPMDh/1/ 这是小提琴: http : //jsfiddle.net/vPMDh/1/
Element.scrollHeight
应该完成这项工作。
It should expand even if being absolute. 即使是绝对的,它也应该扩大。 check you don't have a height: xxpx
检查你没有高度:xxpx
if so, change it to min-height 如果是这样,将其更改为最小高度
use a clearfix hack. 使用clearfix hack。 heres the link
继承人的链接
and add clearfix to you div 并为您添加clearfix
example 例
in your style sheet 在你的样式表中
<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>
... and in your div add clearfix the class ...并在你的div中添加clearfix类
<div class="clearfix">
//some html tags
</div>
As you've said "it doesn't expand if the content is higher than it's height."
如你所说
"it doesn't expand if the content is higher than it's height."
I guess you have a fixed height set on it.. if you do need this for some reason try using min-height
instead. 我猜你有一个固定的高度设置..如果你出于某种原因确实需要这个,请尝试使用
min-height
。
<div class="classname">
Some content....
<p style="clear:both"> </p>
</div>
Thanks for contributing your question. 感谢您提出问题。 If you use this:
如果你使用这个:
$(document).ready(function(){
var x = $("#container").height();
alert(x);
//if not works then
var y = $("#container").outerHeight();
alert(y);
});
I think it is easy as clean code to find the height of any div if you do not apply the div's height too. 我认为如果你不应用div的高度,那么很容易找到任何div的高度。
similar solution to @MattDiamant, but with vanilla JS and without creating a clone: 与@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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.