jQuery min/max property from array of elements

前端 未结 8 1480
陌清茗
陌清茗 2020-11-29 02:09

Is there a simple way to find the min/max property from an array of elements in jQuery?

I constantly find myself dynamically resizing groups of elements based on the

8条回答
  •  悲&欢浪女
    2020-11-29 02:21

    Rolled up as a plugin to return min-max of width and height:

    // 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.
    

提交回复
热议问题