简体   繁体   中英

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. 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. Is there a simple way to do this in jquery? See the following example:

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/

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/

$("#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. If you're looking for the height of the content, the scrollHeight property of the parent will give you that information.

$('#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

Fiddle

try to count the last div (child 4) offset top + child 4 height - parent offset top

try this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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