lau*_*kok 43 css jquery z-index
我有许多具有不同z-index的div元素.我想在这些div中找到最高的z-index - 我怎样才能实现它?
CSS:
#layer-1 { z-index: 1 }
#layer-2 { z-index: 2 }
#layer-3 { z-index: 3 }
#layer-4 { z-index: 4 }
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
我不认为这条线可以找到最高的z指数.
var index_highest = parseInt($("div").css("zIndex"));
// returns 10000
Run Code Online (Sandbox Code Playgroud)
jus*_*tkt 35
请注意,z-index仅影响定位元素.因此,任何position: static具有z-index的元素,即使您为其赋值.在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;
}
});
Run Code Online (Sandbox Code Playgroud)
一般的jQuery选择器,当与返回一个值的选项一起使用时,只会返回第一个.所以你的结果只是jQuery抓取的第一个div的z-index.要仅获取所需的div,请在其上使用类.如果你想要所有的div,坚持下去div.
Aar*_*ner 13
这是一个非常简洁的方法:
var getMaxZ = function(selector){
return Math.max.apply(null, $(selector).map(function(){
var z;
return isNaN(z = parseInt($(this).css("z-index"), 10)) ? 0 : z;
}));
};
Run Code Online (Sandbox Code Playgroud)
用法:
getMaxZ($("#layer-1,#layer-2,#layer-3,#layer-4"));
Run Code Online (Sandbox Code Playgroud)
或者,作为jQuery扩展:
jQuery.fn.extend({
getMaxZ : function(){
return Math.max.apply(null, jQuery(this).map(function(){
var z;
return isNaN(z = parseInt(jQuery(this).css("z-index"), 10)) ? 0 : z;
}));
}
});
Run Code Online (Sandbox Code Playgroud)
用法:
$("#layer-1,#layer-2,#layer-3,#layer-4").getMaxZ();
Run Code Online (Sandbox Code Playgroud)
Ant*_*oly 11
除了@ justkt上面的原生解决方案,有一个很好的插件可以做你想要的.看看TopZIndex.
$.topZIndex("div");
Run Code Online (Sandbox Code Playgroud)
试试这个 :
var index_highest = 0;
$('div').each(function(){
var index_current = parseInt($(this).css("z-index"), 10);
if(index_current > index_highest) {
index_highest = index_current;
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59575 次 |
| 最近记录: |