Get the sum of the outerHeight of all elements of the same class

前端 未结 9 1605
Happy的楠姐
Happy的楠姐 2021-01-03 23:46

I think this is a pretty straightforward problem but...

var outerHeight = $(\'.profile\').outerHeight();
$(\"#total-height\").text(outerHeight + \'px\');
         


        
9条回答
  •  情歌与酒
    2021-01-04 00:10

    You can also be lazy as me and introduce a new jQuery function that will do all the work for you, like this:

    (function($) {    
        $.fn.sumOfOuterHeights = function () {
            var sum = 0;
            $(this).each(function () {
                sum += $(this).outerHeight();
            });
            return sum;
        };
    })(jQuery);
    

    And then use it in your code wherever you like it:

    var height = $('.a, .b, .c').sumOfOuterHeights();
    

    For me it is also a little bit more readable and DRY if you use it often.

提交回复
热议问题