简体   繁体   English

用jQuery获取div的计算高度

[英]get computed height of div with jquery

If I have a div that is positioned relative and then some divs inside that which are positioned absolute the parent div will have no height. 如果我有一个div相对放置,然后其中的一些div绝对放置,则父div将没有高度。 The contents of the div can change though so I need a way to calculate the height of the contents and set the height of the parent dynamically. 尽管div的内容可以更改,所以我需要一种方法来计算内容的高度并动态设置父级的高度。 Is there a simple way to do this in jquery? 有没有一种简单的方法来做到这一点的jQuery? See the following example: 请参见以下示例:

http://jsfiddle.net/vgyrbcbs/ http://jsfiddle.net/vgyrbcbs/

#parent {
    position: relative;
}
.child {
    position: absolute;
    width: 100px;
    height: 100px;
    background: #ff0000;
}  
#child1 {
    top:0;
    left:0
}
#child2 {
    top:50px;
    left:150px;
}
#child3 {
    top:150px;
    left:20px;
}
#child4 {
    top:250px;
    left:150px;
}
<div id="parent">
    <div class="child" id="child1"></div>
    <div class="child" id="child2"></div>
    <div class="child" id="child3"></div>
    <div class="child" id="child4"></div>
</div>

How would I work out the height of the parent? 我将如何计算父母的身高?

Something like this : http://jsfiddle.net/vgyrbcbs/2/ 像这样的东西: http : //jsfiddle.net/vgyrbcbs/2/

var height = 0;

$("#parent div").each(function () {
   height += parseInt($(this).css("height").split("px")[0]);

});

$("#parent").css("height", height);

UPDATE 更新

You can check the last div if it's always at the bottom like this : http://jsfiddle.net/vgyrbcbs/4/ 您可以检查最后一个div是否始终像这样位于底部: http : //jsfiddle.net/vgyrbcbs/4/

$("#parent").css("height", parseInt($("#parent div:last").css("top").split("px")[0]) + parseInt($("#parent div:last").css("height").split("px")[0]));

The parent's height is actually 0 because all the elements are positionned absolutely. 父母的身高实际上是0,因为所有元素都是绝对放置的。 If you're looking for the height of the content, the scrollHeight property of the parent will give you that information. 如果您要查找内容的高度,则父级的scrollHeight属性将为您提供该信息。

$('#parent')[0].scrollHeight; // or
$('#parent').get(0).scrollHeight; // or
$('#parent').prop('scrollHeight'); 

Try: 尝试:

var h = 0;
$('#parent .child').each(function(){h = Math.max($(this).offset().top + $(this).height(), h);})
alert(h);

I just search height as top+height of bottom child element 我只是搜索身高作为底部子元素的top + height

Fiddle 小提琴

try to count the last div (child 4) offset top + child 4 height - parent offset top 尝试计算最后一个div(子级4)偏移量顶部+子级4高度-父级偏移量顶部

try this 尝试这个

var parent_height = $('#child4').height()+$('#child4').offset().top-$('#parent').offset().top;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM