如何计算文档中最高的z索引?

In order to set a div containing a transparent text image as the highest z-index in my document, I picked the number 10,000 and it solved my problem.

Previously I had guessed with the number 3 but it had no effect.

So, is there a more scientific way of figuring out what z-index is higher than that of all of your other elements?

I tried looking for this metric in Firebug but couldn't find it.

#0

Stealing some code from abcoder site for the sake of clarity:

  var maxZ = Math.max.apply(null, 
    $.map($('body *'), function(e,n) {
      if ($(e).css('position') != 'static')
        return parseInt($(e).css('z-index')) || 1;
  }));

#1

You could call findHighestZIndex for a particular element type such as a 'DIV' like this:

findHighestZIndex('div');

assuming a findHighestZindex function that is defined like this:

function findHighestZIndex(elem)
{
  var elems = document.getElementsByTagName(elem);
  var highest = 0;
  for (var i = 0; i < elems.length; i++)
  {
    var zindex=document.defaultView.getComputedStyle(elems[i],null).getPropertyValue("z-index");
    if ((zindex > highest) && (zindex != 'auto'))
    {
      highest = zindex;
    }
  }
  return highest;
}

#2

Using ES6 a cleaner approach

function maxZIndex() {

     return Array.from(document.querySelectorAll('body *'))
           .map(a => parseFloat(window.getComputedStyle(a).zIndex))
           .filter(a => !isNaN(a))
           .sort()
           .pop();
}

#3

There isn't a default property or anything, but you could write some javascript to loop through all elements and figure it out. Or if you use a DOM management library like jQuery, you could extend its methods (or find out if it supports it already) so that it starts tracking element z-indices from page load, and then it becomes trivial to retrieve the highest z-index.

#4

The best way to solve this problem is, in my opinion, just to set yourself conventions for what kinds of z-indexes are used for different kinds of elements. Then, you'll find the correct z-index to use by looking back at your documentation.

#5

I believe what you are observing is Voodoo. Without access to your complete style sheet I can of course not tell reliably; but it strikes me as likely that what really has happened here is that you have forgotten that only positioned elements are affected by z-index.

Additionally, z-indexes aren't assigned automatically, only in style sheets, which means that with no other z-indexed elements, z-index:1; will be on top of everything else.

#6

I’d like to add my ECMAScript 6 implementation that I use in one of my UserScripts. I’m using this one to define the z-index of specific elements so that they always appear the highest. I can exclude these elements with the chained :not selector.

let highestZIndex = 0;

// later, potentially repeatedly
highestZIndex = Math.max(
  highestZIndex,
  ...Array.from(document.querySelectorAll("body *:not([data-highest]):not(.yetHigher)"), (elem) => parseFloat(getComputedStyle(elem).zIndex))
    .filter((zIndex) => !isNaN(zIndex))
);

The lower five lines can run multiple times and update the variable highestZIndex repeatedly by finding out the maximum between the current highestZIndex value and all the other computed z-indices of all elements. The filter excludes all the "auto" values.

#7

I guess you have to do this yourself ...

function findHighestZIndex()
{
    var divs = document.getElementsByTagName('div');
    var highest = 0;
    for (var i = 0; i < divs .length; i++)
    {
        var zindex = divs[i].style.zIndex;
        if (zindex > highest) {
            highest = zindex;
        }
    }
    return highest;
}

#8

I had to do this for a project recently, and I found that I benefitted a lot from @Philippe Gerber's great answer here, and @flo's great answer (the accepted answer).

The key differences to the answers referenced above are:

  • Both the CSS z-index, and any inline z-index style are calculated, and use the larger of the two for comparison and calculation.
  • Values are coerced into integers, and any string values (auto, static, etc) are ignored.

Here is a CodePen for the code example, but it's included here as well.

(() => {
  /**
   * Determines is the value is numeric or not.
   * See: https://stackoverflow.com/a/9716488/1058612.
   * @param {*} val The value to test for numeric type.
   * @return {boolean} Whether the value is numeric or not.
   */
  function isNumeric(val) {
    return !isNaN(parseFloat(val)) && isFinite(val);
  }

  
  /**
   * Finds the highest index in the current document.
   * Derived from the following great examples:
   *  [1] https://stackoverflow.com/a/1118216/1058612
   *  [2] https://stackoverflow.com/a/1118217/1058612
   * @return {number} An integer representing the value of the highest z-index.
   */
  function findHighestZIndex() {
    let queryObject = document.querySelectorAll('*');
    let childNodes = Object.keys(queryObject).map(key => queryObject[key]);
    let highest = 0;
    
    childNodes.forEach((node) => {
      // Get the calculated CSS z-index value.
      let cssStyles = document.defaultView.getComputedStyle(node);
      let cssZIndex = cssStyles.getPropertyValue('z-index');
      
      // Get any inline z-index value.
      let inlineZIndex = node.style.zIndex;

      // Coerce the values as integers for comparison.
      cssZIndex = isNumeric(cssZIndex) ? parseInt(cssZIndex, 10) : 0;
      inlineZIndex = isNumeric(inlineZIndex) ? parseInt(inlineZIndex, 10) : 0;
      
      // Take the highest z-index for this element, whether inline or from CSS.
      let currentZIndex = cssZIndex > inlineZIndex ? cssZIndex : inlineZIndex;
      
      if ((currentZIndex > highest)) {
        highest = currentZIndex;
      }
    });

    return highest;
  }

  console.log('Highest Z', findHighestZIndex());
})();
#root {
  background-color: #333;
}

.first-child {
  background-color: #fff;
  display: inline-block;
  height: 100px;
  width: 100px;
}

.second-child {
  background-color: #00ff00;
  display: block;
  height: 90%;
  width: 90%;
  padding: 0;
  margin: 5%;
}

.third-child {
  background-color: #0000ff;
  display: block;
  height: 90%;
  width: 90%;
  padding: 0;
  margin: 5%;
}

.nested-high-z-index {
  position: absolute;
  z-index: 9999;
}
<div id="root" style="z-index: 10">
  <div class="first-child" style="z-index: 11">
    <div class="second-child" style="z-index: 12"></div>
  </div>
  <div class="first-child" style="z-index: 13">
    <div class="second-child" style="z-index: 14"></div>
  </div>
  <div class="first-child" style="z-index: 15">
    <div class="second-child" style="z-index: 16"></div>
  </div>
  <div class="first-child" style="z-index: 17">
    <div class="second-child" style="z-index: 18">
      <div class="third-child" style="z-index: 19">
        <div class="nested-high-z-index">Hello!!! </div>
      </div>
    </div>
  </div>
  <div class="first-child">
    <div class="second-child"></div>
  </div>
  <div class="first-child">
    <div class="second-child"></div>
  </div>
  <div class="first-child">
    <div class="second-child"></div>
  </div>
</div>

#9

If you're looking to show the IDs of all elements with the highest z indices:

function show_highest_z() {
    z_inds = []
    ids = []
    res = []
    $.map($('body *'), function(e, n) {
        if ($(e).css('position') != 'static') {
            z_inds.push(parseFloat($(e).css('z-index')) || 1)
            ids.push($(e).attr('id'))
        }
    })
    max_z = Math.max.apply(null, z_inds)
    for (i = 0; i < z_inds.length; i++) {
        if (z_inds[i] == max_z) {
            inner = {}
            inner.id = ids[i]
            inner.z_index = z_inds[i]
            res.push(inner)
        }
    }
    return (res)
}

Usage:

show_highest_z()

Result:

[{
    "id": "overlay_LlI4wrVtcuBcSof",
    "z_index": 999999
}, {
    "id": "overlay_IZ2l6piwCNpKxAH",
    "z_index": 999999
}]

#10

Using jQuery:

if no elements supplied, it checks all elements.

function maxZIndex(elems)
{
    var maxIndex = 0;
    elems = typeof elems !== 'undefined' ? elems : $("*");

    $(elems).each(function(){
                      maxIndex = (parseInt(maxIndex) < parseInt($(this).css('z-index'))) ? parseInt($(this).css('z-index')) : maxIndex;
                      });

return maxIndex;
}

#11

A solution highly inspired from the excellent idea of @Rajkeshwar Prasad .

 /**
 returns highest z-index
 @param {HTMLElement} [target] highest z-index applyed to target if it is an HTMLElement.
 @return {number} the highest z-index.
 */
 var maxZIndex=function(target) {
     if(target instanceof HTMLElement){
         return (target.style.zIndex=maxZIndex()+1);
     }else{
         var zi,tmp=Array.from(document.querySelectorAll('body *'))
             .map(a => parseFloat(window.getComputedStyle(a).zIndex));
         zi=tmp.length;
         tmp=tmp.filter(a => !isNaN(a));
         return tmp.length?Math.max(tmp.sort((a,b) => a-b).pop(),zi):zi;
     }
 };
#layer_1,#layer_2,#layer_3{
  position:absolute;
  border:solid 1px #000;
  width:100px;
  height:100px;
}
#layer_1{
  left:10px;
  top:10px;
  background-color:#f00;
}
#layer_2{
  left:60px;
  top:20px;
  background-color:#0f0;
  z-index:150;
}
#layer_3{
  left:20px;
  top:60px;
  background-color:#00f;
}
<div id="layer_1" onclick="maxZIndex(this)">layer_1</div>
<div id="layer_2" onclick="maxZIndex(this)">layer_2</div>
<div id="layer_3" onclick="maxZIndex(this)">layer_3</div>

#12

Array.reduce()

Here's another solution to determine the topmost z-index that uses Array.reduce():

const max_zindex = [...document.querySelectorAll('body *')].reduce((accumulator, current_value) => {
  current_value = +getComputedStyle(current_value).zIndex;

  if (current_value === current_value) { // Not NaN
    return Math.max(accumulator, current_value)
  }

  return accumulator;
}, 0); // Default Z-Index Rendering Layer 0 (Zero)

推荐文章

FirstOrDefault()无法与??操作人员

FirstOrDefault()无法与??操作人员

推荐文章

在没有c编译器的linux上安装gcc

在没有c编译器的linux上安装gcc

推荐文章

是否可以将COM DLL转换为.NET DLL?

是否可以将COM DLL转换为.NET DLL?

推荐文章

在黑莓手机中打开Microsoft Access数据库

在黑莓手机中打开Microsoft Access数据库

推荐文章

在gridview中插入多行

在gridview中插入多行

推荐文章

优化违反注册wpf数据网格

优化违反注册wpf数据网格

推荐文章

realloc如何知道要复制多少?

realloc如何知道要复制多少?

推荐文章

在HTML5翻转卡中沿Z轴旋转

在HTML5翻转卡中沿Z轴旋转

推荐文章

如何将模型字段值传递给javascript变量?

如何将模型字段值传递给javascript变量?

推荐文章

在PHP fopen流中访问Windows的特殊命名文件夹

在PHP fopen流中访问Windows的特殊命名文件夹

推荐文章

网络监控系统

网络监控系统

推荐文章

在我的PHP应用程序中将一个用户分配给多个项目,最佳方法是什么?

在我的PHP应用程序中将一个用户分配给多个项目,最佳方法是什么?

推荐文章

为什么按钮的value属性在IE中指定为false?

为什么按钮的value属性在IE中指定为false?

推荐文章

JSF页面上当前数据的问题

JSF页面上当前数据的问题

推荐文章

Python 3中的Web网关接口

Python 3中的Web网关接口

推荐文章

如何进行查询?

如何进行查询?