How to find the highest z-index within a document

2020-07-10 20:18发布

问题:

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>