来自元素数组的 jQuery min/max 属性 [英] jQuery min/max property from array of elements

查看:67
本文介绍了来自元素数组的 jQuery min/max 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单的方法可以从 jQuery 中的元素数组中找到 min/max 属性?

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

我通常这样做:

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

jQuery 中是否存在此功能,或者有人可以解释如何创建执行此操作的基本插件?

Does this functionality exist in jQuery or can someone explain how to create a basic plugin that does this?

谢谢!

推荐答案

使用 Fast JavaScript Max/Min - John Resig

以 google、yahoo 和 bing 三个标志为例.

Example with three logos of google, yahoo and 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));
});

PS:jsfiddle在这里

这篇关于来自元素数组的 jQuery min/max 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆