Javascript 来自元素数组的 jQuery min/max 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5052673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery min/max property from array of elements
提问by user624598
Is there a simple way to find the min/max property from an array of elements in jQuery?
有没有一种简单的方法可以从 jQuery 中的元素数组中找到 min/max 属性?
I constantly find myself dynamically resizing groups of elements based on the minimum and maximum counterparts. Most of the time this pertains to the width and/or height of an element but I'm sure this could be applied to any property of an element.
我经常发现自己根据最小和最大对应项动态调整元素组的大小。大多数情况下,这与元素的宽度和/或高度有关,但我确信这可以应用于元素的任何属性。
I usually do something like this:
我通常做这样的事情:
var maxWidth = 0;
$('img').each(function(index){
if ($(this).width() > maxWidth)
{
maxWidth = $(this).width();
}
});
But it seems like you should be able to do something like this:
但看起来你应该能够做这样的事情:
var maxWidth = $('img').max('width');
Does this functionality exist in jQuery or can someone explain how to create a basic plugin that does this?
这个功能是否存在于 jQuery 中,或者有人可以解释如何创建一个基本的插件来做到这一点?
Thanks!
谢谢!
回答by naveen
Use Fast JavaScript Max/Min - John Resig
使用Fast JavaScript Max/Min - John Resig
Example with three logos of google, yahoo and bing.
以 google、yahoo 和 bing 三个标志为例。
HTML
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
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 here
PS:jsfiddle在这里
回答by amr
You can use apply
outside the context of OO, no need to extend the prototype:
您可以apply
在 OO 的上下文之外使用,无需扩展原型:
var maxHeight = Math.max.apply( null,
$('img').map(function(){ return $(this).height(); }).get() );
回答by Mottie
I like the elegant solution posted as a .map()
example in the jQuery docs on how to equalize div heights. I basically adapted it to work with widths and made a demo.
我喜欢.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
回答by Michiel Overeem
Take a look at the calculation plugin, maybe it can help you with your problems. They offer a number of math functions, like min, max and avg on DOM-elements.
看看计算插件,也许它可以帮助您解决问题。它们提供了许多数学函数,例如 DOM 元素上的 min、max 和 avg。
Examples:
例子:
$("input[name^='min']").min();
$("input[name^='max']").max();
回答by Neil
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.
回答by Greg
I wrote a simple plugin to do exactly this - see gregbrown.co.nz/code/jquery-aggregate. With it installed, you could do:
我写了一个简单的插件来做到这一点 - 请参阅gregbrown.co.nz/code/jquery-aggregate。安装它后,您可以执行以下操作:
var maxWidth = $('img').aggregate('width', 'max');
var maxWidth = $('img').aggregate('width', 'max');
回答by bigOmega
You can use native "sort" function to have more control over which elements are compared
您可以使用本机“排序”功能来更好地控制比较哪些元素
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);
};
and you can call it like
你可以这样称呼它
var maxWidth = $('img').deepMax(function(a, b){
//-1 if a < b; +1 otherwise
return $(a).width() - $(b).width();
});
OR
或者
you can use _.maxof Underscorewhich is can be implemented like...
您可以使用下划线的_.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();});
回答by sdleihssirhc
The Plugins/Authoring pageactually has an example for determining the tallest element.
所述插件/创作页实际上具有用于确定所述最高的元素的例子。
It's basically what you have here, just rolled into a plugin for easy access. Maybe you could appropriate it for your uses.
它基本上就是你在这里拥有的,只是滚动到一个插件中以便于访问。也许您可以将其用于您的用途。