jquery finding the total height of all divs childr

2019-06-21 04:57发布

问题:

hey I have a div with 5 div's contained in it, I want to add all of their heights together,

This is the solution I ended up using based off of Jeff's answer. Thanks for helping me out.

var ev_totalHeight = 0;
$("#events > div").each(function(){
    ev_totalHeight += $(this).innerHeight();
});



function events_open() {
 $("#events").animate({
"height": ev_totalHeight
  }, 450 );
}

$("#events").click(function() {
events_open();
});

回答1:

Heres a fiddle: http://jsfiddle.net/yj8sL/2/

$(function(){
    var totalHeight = 0;
    $("#parent > div").each(function(){
        totalHeight += $(this).height();
    });
    alert("Total height of all divs: "+totalHeight);
});

As you see, there are 5 divs, with a height of 100px each, so the total height is 500px.

EDIT: Your next problem (with the animate) is that you are not telling it what unit you are using (in your case, pixels):

 $("#events").animate({
    "height": ev_totalHeight+"px"
 }, 450 );


回答2:

Something along these lines:

var height = 0;

$('#events > div').each(function(){
    height += $(this).height();
});

// apply calculated height to another element
$('#myotherdiv').height(height + 'px');


回答3:

Loop through them all and add the height e.g.

var height;
$("#events").each(function() {
    height += $(this).height();
});