题
为了将包含透明文本图像的 div 设置为文档中的最高 z-index,我选择了数字 10,000,它解决了我的问题。
之前我曾猜过数字3,但没有效果。
那么,是否有更科学的方法来确定哪个 z-index 高于所有其他元素的 z-index?
我尝试在 Firebug 中查找此指标,但找不到。
解决方案
您可以调用特定元件类型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;
}
其他提示
窃取从abcoder站点一些代码为清楚起见:
var maxZ = Math.max.apply(null,
$.map($('body *'), function(e,n) {
if ($(e).css('position') != 'static')
return parseInt($(e).css('z-index')) || 1;
}));
使用ES6清洁器的方法
function maxZIndex() {
return Array.from(document.querySelectorAll('body *'))
.map(a => parseFloat(window.getComputedStyle(a).zIndex))
.filter(a => !isNaN(a))
.sort()
.pop();
}
解决这个问题的最好办法是,在我看来,只要自己设定了什么样的z-index
es的用于不同种类的元素约定。然后,你会找到正确的z-index
通过在你的文档回头使用。
我相信你正在观察什么是巫术。如果无法访问您的完整样式表我当然不会告诉可靠;但它给我的印象可能是真正在这里发生的事情是,你已经忘记了,只定位的元素被z-index
影响。
此外,z-index
es不会自动分配,只在样式表中,这意味着,没有其他z-index
ed元素,z-index:1;
将在一切之上。
我想你必须这样做自己......
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;
}
有没有默认属性什么的,但你可以通过所有的元素写一些javascript循环和看着办吧。或者,如果你使用DOM管理库如jQuery,你可以扩展它的方法(或了解其是否支持它的话),以便它开始从页面加载跟踪元素的z索引,然后将它变得微不足道检索最高Z-索引。
我想加我的,我在我的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
的电流 highestZIndex
值和所有其他计算的所有元素的z折射率。所述filter
排除所有的"auto"
值。
最近要做一个项目,发现自己受益匪浅 @菲利普·格伯这里有很好的答案,并且 @弗洛很好的答案(已接受的答案)。
与上述答案的主要区别是:
- 两者都是CSS
z-index
, ,以及任何内联z-index
style 进行计算,取两者中较大者进行比较计算。 - 值被强制转换为整数,并且任何字符串值 (
auto
,static
, 等)被忽略。
这里 是代码示例的 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>
使用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;
}
如果你正在寻找显示的ID的所有的最高z折射率元素
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
}]
一个解决方案深受以下优秀想法的启发 @拉吉克什瓦尔·普拉萨德 .
/**
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>
Array.reduce()
下面是另一种解决方案,以确定最上面 z-index
一>使用 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)
考虑这个代码,可以作为库使用: getMaxZIndex