如何使用jQuery找到最高的z-index [英] How to find the highest z-index using jQuery

查看:125
本文介绍了如何使用jQuery找到最高的z-index的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些div元素具有不同的z-index。

I have a number of div elements with different z-index. And I want to find the highest z-index among these divs - how can I achieve it?

CSS:

#layer-1 { z-index: 1 }
#layer-2 { z-index: 2 }
#layer-3 { z-index: 3 }
#layer-4 { z-index: 4 }



HTML:

<div id="layer-1">layer-1</div>
<div id="layer-2">layer-2</div>
<div id="layer-3">layer-3</div>
<div id="layer-4">layer-4</div>

我不认为这行可以找到最高的z-索引。

I don't think this line can find the highest z-index though.

var index_highest = parseInt($("div").css("zIndex"));
// returns 10000


推荐答案

-index只影响定位的元素。因此,任何具有 position:static 的元素都不会有z-index,即使您为其分配了一个值。这在诸如Google Chrome浏览器中尤其如此。

Note that z-index only affects positioned elements. Therefore, any element with position: static will not have a z-index, even if you assign it a value. This is especially true in browsers like Google Chrome.

var index_highest = 0;   
// more effective to have a class for the div you want to search and 
// pass that to your selector
$("#layer-1,#layer-2,#layer-3,#layer-4").each(function() {
    // always use a radix when using parseInt
    var index_current = parseInt($(this).css("zIndex"), 10);
    if(index_current > index_highest) {
        index_highest = index_current;
    }
});

JSFiddle demo

一个通用的jQuery选择器,当使用返回一个值的选项时,只会返回第一个所以你的结果只是z- jQuery抓取的第一个div的索引。要只抓住你想要的div,在它们上面使用一个类。如果你想要所有的div,坚持使用 div

A general jQuery selector like that when used with an option that returns one value will merely return the first So your result is simply the z-index of the first div that jQuery grabs. To grab only the divs you want, use a class on them. If you want all divs, stick with div.

这篇关于如何使用jQuery找到最高的z-index的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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