How to find the highest z-index within a document no matter what tags they are?

最后都变了- 提交于 2019-12-21 13:03:06

问题


How can I find the highest z-index within a document no matter what tags they are?

I found this code but I tested it and it does not work,

//include jQuery.js --  visit: http://jquery.com/
$(function(){
    var maxZ = Math.max.apply(null,$.map($('body > *'), function(e,n){
           if($(e).css('position')=='absolute')
                return parseInt($(e).css('z-index'))||1 ;
           })
    );
    alert(maxZ);
});

Any better approach to do this?

EDIT:

It seems to work if I change the code to this,

$('body *')

$('body > *') --> is for div only I guess.

回答1:


This isn't the most efficient solution, but it should work. jsFiddle.

Please note you have to have a position specified in order for the z-index to return a value.

var highest = -999;

$("*").each(function() {
    var current = parseInt($(this).css("z-index"), 10);
    if(current && highest < current) highest = current;
});

alert(highest);



回答2:


This seems to work:

var maxZ=0;
$('*').each(function(){
    if($(this).css('zIndex') > maxZ) maxZ = $(this).css('zIndex');
})
console.log(maxZ);

jsFiddle example

I think one of the issues with the code you posted is that you're only checking for absolutely positioned elements.




回答3:


Just to add a solution without jQuery:

let all= Array.from(document.querySelectorAll('body *'));
console.log('Found ',all.length,' elements');
let allIndexes=all.map((elem)=>{
  if (elem.style) {
    return +elem.style.zIndex || 0;
  }
  return -9999;
});

let max=Math.max.apply(null,allIndexes);
console.log('Max z-index:',max);
.cl {
position: absolute;
border: 1px solid;
}
<div class="cl" style="z-index: 3;width:100px;height:100px;background:#A00;"></div>
<div class="cl" style="z-index: 4;width:90px;height:90px;background:#0A0;"></div>
<div class="cl" style="z-index: 5;width:50px;height:50px;background:#AA0;"></div>
<div class="cl" style="z-index: 6;width:40px;height:40px;background:#AAA"></div>


来源:https://stackoverflow.com/questions/17686544/how-to-find-the-highest-z-index-within-a-document-no-matter-what-tags-they-are

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!