开发者

Calculate height of div's children using jQuery

I want to match parent's height with the total height of its' children, so the content does not flow out from parent's border. I'm using the following code :

 $("#leftcolumn").each(function(){
     totalHeight=totalHeight+$(this).height();
  });

Will it iterate through all the div's children? Sometimes, it works sometimes it doesn't.

Also, I tried following code, assuming it will consider all its children. But the result is strange and gives doubled height from the correct r开发者_如何学编程esult.

 $("#leftcolumn > *").each(function(){
   totalHeight=totalHeight+$(this).height();
 });

Thanks in advance.


Try it like so:

var totalHeight = 0;

$("#leftcolumn").children().each(function(){
    totalHeight = totalHeight + $(this).outerHeight(true);
});

http://api.jquery.com/outerHeight/ takes margins, paddings and borders into the calculation which should return a more reliable result.


Another approach is calculating the distance between the top- and bottommost offsets within the element, which would account for any non-static positioned elements.

I've only tested this in one page and environment, so I'm not at all sure how safe it is to use. Please post a comment if be very bad codes or if it deserves some improvement.

var topOffset = bottomOffset = 0,
    outer = true;
$el.children().each(function(i, e){
    var $e = $(e),
        eTopOffset = $e.offset().top,
        eBottomOffset = eTopOffset + (outer ? $e.outerHeight() : $e.height());

    if (eTopOffset < topOffset) {
        topOffset = eTopOffset;
    }
    if (eBottomOffset > bottomOffset) {
        bottomOffset = eBottomOffset;
    }
});

var childrenHeight = bottomOffset - topOffset - $el.offset().top;


If you want to ignore hidden elements, you can filter them out:

$("#leftcolumn").children().filter(':visible').each(function(){
    totalHeight += $(this).outerHeight();
});


How about like this. Does not require you to mutate a variable in an outer scope, allows you to reuse the sumHeights function.

function sumHeights(height, element) {
    return height + $(element).outerHeight(true);
}

const outerHeight = $('#leftcolumn')
    .children()
    .toArray()
    .reduce(sumHeights, 0);


 $('#leftColumn').children().each(function(){
    var Totalheight += $(this).Height();
})var parentHeight = $('#leftColumn').Height();
if(parentHeight===TotalHeight)
{//Do the nasty part}
else
{//Do the Good part}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜