0

なんてこった!

次のjQuery関数を見てみましょう。

$.fn.getMax = function() {
    return this.height(Math.max.apply(this, $(this).map(function(i, e) {
        return $(e).height();
    }).get()));
};

すべてのセレクターの最も高い高さを返し、設定します。objectしかし、 (高さではなく)最も高い値を返したい場合はどうでしょうか。

したがって、次のように関数を呼び出すと、次のようになります。

$(selector).getMax().css({backgroundColor: "indigo"});

...最も高い高さの要素はどのように取得されbackgroundColorますか?

アップデート

Amareswar$.makeArrayが言ったように、私は今それをで管理しました。

$.fn.getMax = function(prop) {
    var max = $.makeArray($(this)).sort(function(a, b) {
        return (parseInt($(b).css(prop), 10) || 1) - (parseInt($(a).css(prop), 10) || 1);
    }).shift();
    return $(max);
};

乾杯!

4

1 に答える 1

0

これを試して:

$.fn.getMax = function() {
     /* create array of heights*/
    var heights = $(this).map(function(i, e) {
        return $(e).height();
    }).get();
    /* get max height*/
    var max = Math.max.apply(this, heights);
    /* get index of max in array*/
    var pos = $.inArray(max, heights)
    /* return element with proper index*/
    return this.eq(pos);
};

デモ:http://jsfiddle.net/tTuE7/

編集:1つの要素のみが返されることを前提としています

于 2012-11-10T14:21:51.917 に答える