Calculate largest width of a set of elements using jQuery

后端 未结 7 1002
轻奢々
轻奢々 2020-12-16 03:07

I have made a quick Jsbin: http://jsbin.com/ujabew/edit#javascript,html,live

What i\'m trying to achieve is to find out which is the largest

相关标签:
7条回答
  • 2020-12-16 03:50

    I have just written a function regarding this. I thought it might help others. (jQuery)

    $.fn.largerWidth = function () {    //function(p)  
                                        // where 'p' can be clientWidth or offsetWidth 
                                        // or anything else related to width or height
        var s = this,m;
        for (var i = 0; i < s.length; i++) {
            var w = s[i].offsetWidth;   // s[i][p]; 
            (!m || w > m) ? (m = w) : null
        }
        return m;
    }
    
    0 讨论(0)
  • 2020-12-16 03:51

    Change the .each() loop to this:

    var thisWidth = $(this).outerWidth(true);
    
    if (thisWidth > width) {
        width = thisWidth;
    }
    
    0 讨论(0)
  • 2020-12-16 03:57

    I believe you want to look into the underscore library. Specifically, the max method

    0 讨论(0)
  • 2020-12-16 04:02
    $(document).ready(function(){
      var maxWidth = 0;
      $('section').each(function(){
        w = $(this).outerWidth(true);      
        if ( w > maxWidth)
                maxWidth = w;
      });
    });
    
    0 讨论(0)
  • 2020-12-16 04:05

    This was my idea:

    $(document).ready(function () {
      var elements = $(".content ul li");
      var count = elements.length - 1;
      var width = [];
    
      elements.each(function (n) {
        width.push($(this).outerWidth(true));
        if (count == n) {
          width = Math.max.apply(Math, width);
        }
      });
    });
    

    I added the count of the number of elements and then runs the Math.max to get the largest number when each loop is done.

    0 讨论(0)
  • 2020-12-16 04:08

    Fleshing out Marc B's comment, using Math.max():

    $(document).ready(function(){
      var maxWidth = 0;
      $('.content ul li').each(function(){
        var itemWidth = $(this).outerWidth(true);
        maxWidth = Math.max(maxWidth, itemWidth)
      });
    });
    
    0 讨论(0)
提交回复
热议问题