使用jquery选择具有最高z-index的元素

时间:2012-04-28 13:02:11

标签: jquery

我有一个页面,其中我有多个元素与类aaw但具有不同的zIndex。 现在我想选择具有最高zIndex和类aaw的元素。

3 个答案:

答案 0 :(得分:5)

var best;
var maxz;    
$('.aaw').each(function(){
    var z = parseInt($(this).css('z-index'), 10);
    if (!best || maxz<z) {
        best = this;
        maxz = z;
    }
});

结果最好。

Demonstration (open the console)

答案 1 :(得分:3)

jsFiddle:http://jsfiddle.net/A5FUL/31/

<div class="aaw" style="position:relative;z-index:1;">1</div>
<div class="aaw" style="position:relative;z-index:2;">2</div>
<div class="aaw" style="position:relative;z-index:3;">3</div>

<div onclick="test()">Click</div>


<script>
    function test()
    {
        var highest;
        var object;

        $('.aaw').each( function(index)
        {
            if ( index == 0 || $(this).css("z-index") > highest )
            {
                highest = $(this).css("z-index");
                object = $(this);
            }
        });

        alert( $(object).html() );
    }
</script>

答案 2 :(得分:-1)

您可以使用以下内容;

var highestzindex = 0; 
var resultelement = null;  
$(".aaw").each(function() {
    var currentzindex = parseInt($(this).css("zIndex"), 10);
    if(currentzindex > highestzindex) {
        highestzindex = currentzindex;
        resultelement = $(this);
    }
});

我添加了一个demo.You可以看到here