【问题标题】:jQuery min/max property from array of elements来自元素数组的 jQuery 最小/最大属性
【发布时间】:2011-02-19 18:24:31
【问题描述】:

有没有一种简单的方法可以从 jQuery 中的元素数组中找到 min/max 属性?

我经常发现自己会根据最小和最大对应项动态调整元素组的大小。大多数情况下,这与元素的宽度和/或高度有关,但我确信这可以应用于元素的任何属性。

我通常会这样做:

var maxWidth = 0;

$('img').each(function(index){
if ($(this).width() > maxWidth)
{
maxWidth = $(this).width();
}
});

但看起来你应该能够做这样的事情:

var maxWidth = $('img').max('width');

此功能是否存在于 jQuery 中,或者有人可以解释如何创建一个基本插件来执行此操作吗?

谢谢!

【问题讨论】:

    标签: javascript jquery arrays


    【解决方案1】:

    使用Fast JavaScript Max/Min - John Resig

    以 google、yahoo 和 bing 三个标志为例。

    HTML

    <img src="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png" alt="Google Logo" /><br/>
    <img src="http://l.yimg.com/a/i/ww/met/yahoo_logo_in_061509.png" alt="Yahoo Logo" /><br/>
    <img src="http://www.bing.com/fd/s/a/h1.png" alt="Bing Logo" />
    

    Javascript

    $(document).ready(function(){
        // Function to get the Max value in Array
        Array.max = function( array ){
            return Math.max.apply( Math, array );
        };
    
        // Function to get the Min value in Array
        Array.min = function( array ){
           return Math.min.apply( Math, array );
        };
    
        //updated as per Sime Vidas comment.
        var widths= $('img').map(function() {
            return $(this).width();
        }).get();
    
        alert("Max Width: " + Array.max(widths));
        alert("Min Width: " + Array.min(widths));
    });
    

    PS:jsfiddle here

    【讨论】:

    • 更简单:var widths = $('img').map(function() { return $(this).width(); }).get(); 演示:jsfiddle.net/HkxJg/1
    【解决方案2】:

    你可以在OO的上下文之外使用apply,不需要扩展原型:

    var maxHeight = Math.max.apply( null,
            $('img').map(function(){ return $(this).height(); }).get() );
    

    【讨论】:

      【解决方案3】:

      我喜欢在如何equalize div heights 的 jQuery 文档中以.map() 示例发布的优雅解决方案。我基本上将它调整为使用宽度并制作了a demo。

      $.fn.limitWidth = function(max){
        var limit = (max) ? 'max' : 'min';
        return this.width( Math[limit].apply(this, $(this).map(function(i,e){
         return $(e).width();
        }).get() ) );
      };
      
      // Use the function above as follows
      $('.max-width').limitWidth(true); // true flag means set to max
      $('.min-width').limitWidth();     // no flag/false flag means set to min
      

      【讨论】:

      • 喜欢这个答案,谢谢!感谢: - 避免猴子修补数组 - 链接到 jQuery 文档中的示例 - 使用 jQuery 插件?
      【解决方案4】:

      看看calculation plugin,也许它可以帮助你解决你的问题。 它们提供了许多数学函数,例如 DOM 元素的 min、max 和 avg。

      例子:

      $("input[name^='min']").min();
      $("input[name^='max']").max();
      

      【讨论】:

        【解决方案5】:

        作为插件卷起来返回最小-最大宽度和高度:

        // Functions to get the Min & Max value in Array
        
        if (!Array.min) { Array.min = function( array ){return Math.min.apply( Math, array )} }
        if (!Array.max) { Array.max = function( array ){return Math.max.apply( Math, array )} }
        
        (function( $ ){     // Standard jQuery closure to hide '$' from other libraries.
        
            // jQuery plug-in to get the min and max widths of a set of elements
        
            $.fn.dimensionsMinMax = function(whnx) {
        
            /*
            ################################################################################
        
            Name
            ====
        
                dimensionsMinMax(whnx) - jQuery plug-in to get min & max width & height
        
            Parameters
            ==========
        
                whnx - A 4-element array to receive the min and max values of the elements:
                    whnx[0] = minimum width;
                    whnx[1] = maximum width;
                    whnx[2] = minimum height;
                    whnx[3] = maximum height.
        
            Returns
            =======
        
                this - so it can be "chained".
        
            Example
            =======
        
                var minmax = new Array(4);
                var number_of_images = $('img').dimensionsMinMax(minmax).class('abc').length;
                console.log('number of images = ', number_of_images);
                console.log('width  range = ', minmax[0], ' to ', minmax[1]);
                console.log('height range = ', minmax[2], ' to ', minmax[3]);
        
            ################################################################################  
            */
                var  widths = new Array(this.length);
                var heights = new Array(this.length);
        
                this.each(function(i){
                    $this      = $(this);
                     widths[i] = $this.width();
                    heights[i] = $this.height(); 
                });
        
                whnx[0] = Array.min( widths);
                whnx[1] = Array.max( widths);
                whnx[2] = Array.min(heights);
                whnx[3] = Array.max(heights);
        
                return this;
            }
        
        })( jQuery );   // End of standard jQuery closure.
        

        【讨论】:

          【解决方案6】:

          我写了一个简单的插件来做到这一点——见gregbrown.co.nz/code/jquery-aggregate。安装后,您可以:

          var maxWidth = $('img').aggregate('width', 'max');

          【讨论】:

            【解决方案7】:

            您可以使用本机“排序”功能来更好地控制比较哪些元素

            Array.prototype.deepMax = function(comparator){
              if(typeof comparator === 'function'){
                var sorted = this.slice(0).sort(comparator);
                return sorted[sort.length - 1];
              }
              return Math.max.apply(Math, this);
            };
            

            你可以这样称呼它

            var maxWidth = $('img').deepMax(function(a, b){
              //-1 if a < b; +1 otherwise
              return $(a).width() - $(b).width();
            });
            

            或

            您可以使用Underscore 的_.max,可以像...一样实现...

            Array.prototype.max = function(iterator){
              if(!iterator && obj[0] === +obj[0])
                return Math.max.apply(Math, this);
              var result = -Infinity, lastComputed = -Infinity;
              this.forEach(function(value, index){
                var computed = iterator ? iterator(value, index, this) : value;
                computed > lastComputed && (result = value, lastComputed = computed);
              });
              return result;
            };
            
            var maxWidth = $('img').max(function(val){ return $(val).width();});
            

            【讨论】:

              【解决方案8】:

              Plugins/Authoring page 实际上有一个确定最高元素的示例。

              它基本上就是你在这里所拥有的,只是为了方便访问而加入了一个插件。也许您可以将其用于您的用途。

              【讨论】:

                猜你喜欢
                • 2012-10-17
                • 1970-01-01
                • 2013-12-15
                • 1970-01-01
                • 1970-01-01
                • 2020-08-09
                • 1970-01-01
                • 1970-01-01
                • 2017-01-17
                相关资源
                最近更新 更多