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

前端 未结 9 1458
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.

    0 讨论(0)
  • 2021-01-04 00:16

    You can use get an array of the native elements and reduce to get the sum.

    This might be cleaner because it's one line without the need to declare a variable in advance.

    const height = $('div').get().reduce((prev, curr) => prev + curr.offsetHeight, 0);
    console.log(height);
    .child1 {
      height: 30px;
      background: red;
    }
    
    .child2 {
      height: 50px;
      background: green;
    }
    
    .child3 {
      height: 10px;
      background: blue;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="child1"></div>
    <div class="child2"></div>
    <div class="child3"></div>

    This approach can be used without jQuery of course. The [...] thing is to convert NodeList to an array of elements)

    const height = [...document.querySelectorAll('div')].reduce((prev, curr) => prev + curr.offsetHeight, 0);
    console.log(height);
    .child1 {
      height: 30px;
      background: red;
    }
    
    .child2 {
      height: 50px;
      background: green;
    }
    
    .child3 {
      height: 10px;
      background: blue;
    }
    <div class="child1"></div>
    <div class="child2"></div>
    <div class="child3"></div>

    0 讨论(0)
  • 2021-01-04 00:25

    $("selector") is already a collection. Access directly the .outerHeight() or any other method like .height()

    var total = 0;
    $("div").outerHeight(function(i, v){
       total += v;
    });
    
    alert( total ); // Just to test
    

    var total = 0;
    
    $("div").outerHeight(function(i, v){ total += v; });
    
    alert( total );
    div{background:#eee; margin:3px;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div style="height:100px;">100px</div>
    <div>just lots of breaklines :)<br><br><br><br></div>
    <div style="height:200px;">200px</div>

    0 讨论(0)
提交回复
热议问题