¿Existe una forma sencilla de encontrar la propiedad min/max de una matriz de elementos en jQuery?
Constantemente me encuentro cambiando dinámicamente el tamaño de grupos de elementos en función de las contrapartes mínimas y máximas. La mayoría de las veces esto se refiere al ancho y/o alto de un elemento, pero estoy seguro de que esto podría aplicarse a cualquier propiedad de un elemento.
Yo suelo hacer 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!
Usar 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í
Puede usar apply fuera del contexto de OO, no es necesario extender el prototipo:
var maxHeight = Math.max.apply( null, $('img').map(function(){ return $(this).height(); }).get() );Me gusta la solución elegante publicada como un ejemplo de .map() en los documentos de jQuery sobre cómo igualar las alturas de div . Básicamente lo adapté para trabajar con anchos e hice una demostración .
$.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