如何计算文档中最高的z-index?

问题描述 投票:59回答:13

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

以前我猜过3号但是没有效果。

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

我试图在Firebug中寻找这个指标但却找不到它。

html css z-index
13个回答
34
投票

您可以将findHighestZIndex称为特定元素类型,例如'DIV',如下所示:

findHighestZIndex('div');

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

0
投票

使用jQuery:

如果没有提供元素,它会检查所有元素。

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

0
投票

如果您要显示具有最高z索引的所有元素的ID:

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

用法:

show_highest_z()

结果:

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

0
投票

一个高度灵感来自@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>

-1
投票

考虑一下您可以用作库的代码:getMaxZIndex


40
投票

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

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

13
投票

使用ES6更清洁的方法

function maxZIndex() {

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

4
投票

在我看来,解决这个问题的最好方法就是为自己设定各种z-indexes用于不同类型元素的惯例。然后,通过回顾您的文档,您将找到正确使用的z-index


4
投票

我相信你观察的是巫毒。如果没有完整的样式表,我当然无法可靠地说出来;但这让我感到很震惊的是,这里真正发生的事情是你忘记了只有定位元素会受到z-index的影响。

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


4
投票

我想你必须自己做...

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

4
投票

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


3
投票

我想在我的一个UserScripts中添加我使用的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))
);

较低的五行可以多次运行并通过找出当前highestZIndex值与所有其他所有元素的计算z指数之间的最大值来重复更新变量highestZIndexfilter排除了所有"auto"值。


1
投票

我最近必须为一个项目做这个,我发现我从@Philippe Gerber这里的好答案中受益匪浅,并且@flo的答案很好(接受的答案)。

与上述答案的主要区别在于:

  • 计算CSS z-index和任何内联z-index样式,并使用两者中较大的一个进行比较和计算。
  • 值被强制转换为整数,并且忽略任何字符串值(autostatic等)。

Here是代码示例的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>
© www.soinside.com 2019 - 2024. All rights reserved.