Подтвердить что ты не робот

Свойство jQuery min/max из массива элементов

Есть ли простой способ найти свойство min/max из массива элементов в jQuery?

Я постоянно нахожу себя динамически изменяющим размеры групп элементов на основе минимальных и максимальных копий. В большинстве случаев это относится к ширине и/или высоте элемента, но я уверен, что это можно применить к любому свойству элемента.

Обычно я делаю что-то вроде этого:

var maxWidth = 0;

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

Но похоже, что вы должны сделать что-то вроде этого:

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

Эта функция существует в jQuery или может кто-нибудь объяснить, как создать базовый плагин, который делает это?

Спасибо!

4b9b3361

Ответ 1

Используйте Быстрый 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));
});

P.S: jsfiddle здесь

Ответ 2

Вы можете использовать apply вне контекста OO, не нужно расширять прототип:

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

Ответ 3

Мне нравится элегантное решение, размещенное как пример .map() в документах jQuery о том, как выравнивать высоту div. Я в основном адаптировал его для работы с шириной и сделал демо.

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

Ответ 4

Взгляните на плагин , возможно, он поможет вам в решении ваших проблем. Они предлагают ряд математических функций, таких как min, max и avg на DOM-элементах.

Примеры:

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

Ответ 5

Сдвинут как плагин для возврата min-max ширины и высоты:

// 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();
});

ИЛИ

вы можете использовать _. max Underscore, который может быть реализован как...

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

На странице Плагины/Авторская страница есть пример для определения самого высокого элемента.

Это в основном то, что у вас здесь, просто ввернулось в плагин для легкого доступа. Возможно, вы могли бы использовать его для своих целей.