Html 如何找出文档中最高的 z-index?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1118198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:13:57  来源:igfitidea点击:

How can you figure out the highest z-index in your document?

htmlcssz-index

提问by Charlie Kotter

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.

为了将包含透明文本图像的 div 设置为文档中最高的 z-index,我选择了数字 10,000,它解决了我的问题。

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

以前我猜过数字 3,但没有效果。

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

那么,是否有更科学的方法来确定哪个 z-index 高于所有其他元素的 z-index?

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

我尝试在 Firebug 中查找此指标,但找不到。

采纳答案by flo

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

您可以findHighestZIndex像这样调用特定的元素类型,例如“DIV”:

findHighestZIndex('div');

assuming a findHighestZindexfunction that is defined like this:

假设一个findHighestZindex定义如下的函数:

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;
}

回答by Jimmy Chandra

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

为了清楚起见,从 abcoder 站点窃取一些代码:

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

回答by Rajkeshwar Prasad

Using ES6 a cleaner approach

使用 ES6 更简洁的方法

function maxZIndex() {

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

回答by user4642212

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-indexof specific elements so that they always appear the highest. I can exclude these elements with the chained :notselector.

我想添加我在我的用户脚本之一中使用的 ECMAScript 6 实现。我正在使用这个来定义z-index特定元素的 ,以便它们始终显示在最高位置。我可以使用链式:not选择器排除这些元素。

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 highestZIndexrepeatedly by finding out the maximum between the currenthighestZIndexvalue and all the other computed z-indices of all elements. The filterexcludes all the "auto"values.

下面的五行可以多次运行并highestZIndex通过找出当前highestZIndex值和所有其他元素的所有其他计算 z 索引之间的最大值来重复更新变量。在filter排除所有的"auto"值。

回答by Philippe Gerber

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;
}

回答by Rahul

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.

没有默认属性或任何东西,但您可以编写一些 javascript 来遍历所有元素并找出答案。或者,如果你使用像 jQuery 这样的 DOM 管理库,你可以扩展它的方法(或者看看它是否已经支持它),以便它从页面加载开始跟踪元素 z-indices,然后检索最高 z-indices 变得微不足道。指数。

回答by Gareth

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-indexto use by looking back at your documentation.

在我看来,解决这个问题的最好方法是,z-index为不同类型的元素使用什么样的es来设置自己的约定。然后,您将z-index通过回顾您的文档找到正确的使用方法。

回答by Williham Totland

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.

我相信你所观察的是巫毒教。如果无法访问您的完整样式表,我当然无法可靠地判断;但我觉得这里真正发生的事情很可能是你忘记了只有定位元素受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.

此外,z-indexes 不会自动分配,仅在样式表中,这意味着没有其他z-indexed 元素,z-index:1;将位于其他所有元素之上。

回答by JohnnyCoder

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).

我最近不得不为一个项目执行此操作,我发现我从@Philippe Gerber在这里的出色回答和@flo的出色回答(已接受的答案)中受益匪浅

The key differences to the answers referenced above are:

与上述答案的主要区别是:

  • Both the CSS z-index, and any inline z-indexstyle 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.
  • 计算CSSz-index和任何内联z-index样式,并使用两者中较大的一个进行比较和计算。
  • 值被强制成整数,任何字符串值(autostatic,等)将被忽略。

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

是代码示例的 CodePen,但它也包含在此处。

(() => {
  /**
   * 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>

回答by yorg

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

一个受到@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>