number javascript jquery arrays

javascript - number - Propiedad jQuery min/max de la matriz de elementos



max number input jquery (8)

¿Hay una forma sencilla de encontrar la propiedad min / max de una serie de elementos en jQuery?

Constantemente me encuentro redimensionando dinámicamente grupos de elementos basados ​​en las contrapartes mínimas y máximas. La mayoría de las veces esto se refiere al ancho y / o la altura de un elemento, pero estoy seguro de que esto podría aplicarse a cualquier propiedad de un elemento.

Generalmente hago algo como esto:

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

Pero parece que deberías poder hacer algo como esto:

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

¿Existe esta funcionalidad en jQuery o alguien puede explicar cómo crear un complemento básico que haga esto?

¡Gracias!


Eche un vistazo al complemento de cálculo , tal vez pueda ayudarle con sus problemas. Ofrecen una serie de funciones matemáticas, como min, max y avg en elementos DOM.

Ejemplos:

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


Escribí un complemento simple para hacer exactamente esto, ver gregbrown.co.nz/code/jquery-aggregate . Con él instalado, podrías hacer:

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


La página de Complementos / Creación en realidad tiene un ejemplo para determinar el elemento más alto.

Básicamente es lo que tienes aquí, simplemente enrollado en un complemento para un fácil acceso. Tal vez usted podría apropiarse de él para sus usos.


Me gusta la solución elegante publicada como ejemplo de .map() en los documentos de jQuery sobre cómo igualar div alturas . Básicamente lo adapté para trabajar con anchos e hice una 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


Puede usar la función nativa de "clasificación" para tener más control sobre qué elementos se comparan

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

y puedes llamarlo como

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

O

puede usar _.max de Underscore que se puede implementar como ...

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


Puede utilizar la apply fuera del contexto de OO, sin necesidad de extender el prototipo:

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


Se enrolla como complemento para devolver el mínimo y máximo de ancho y alto:

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


Use Fast JavaScript Max / Min - John Resig

Ejemplo con tres logos de google, yahoo y 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)); });

PD: jsfiddle aquí