使用jQuery添加每个匹配元素的高度

时间:2011-07-29 03:21:18

标签: jquery css

我有这个功能

            $('.gallery').each(function(){
                var thumbCount = $(this).find('.ngg-gallery-thumbnail-box').size();
                var rows = thumbCount/5;
                var height = rows*145;
                $(this).css({'height':height+24});
            });

获得每个.gallery div的高度。我想更进一步,从每个函数中取出所有height变量并将它们加在一起(获得所有.gallery div的总高度) - 但我不知道如何。

有人能告诉我正确的语法吗?

谢谢!

1 个答案:

答案 0 :(得分:4)

使用您当前的代码:

var totalHeight = 0;
$('.gallery').each(function(){
    var thumbCount = $(this).find('.ngg-gallery-thumbnail-box').size();
    var rows = thumbCount/5;
    var height = rows*145;
    totalHeight += height;
    $(this).css({'height':height+24});
});

顺便说一句,这就是我如何简化你现有的代码:

var totalHeight = 0;

$('.gallery').each(function(){
    var thumbCount = $(this).find('.ngg-gallery-thumbnail-box').length,
        rows = thumbCount/5,
        height = rows*145;

    totalHeight += height;

    $(this).css('height', height+24);
});