gpt4 book ai didi

javascript - 获取页面上每个元素的 Z-index

转载 作者:行者123 更新时间:2023-11-30 08:38:29 25 4
gpt4 key购买 nike

我试图在页面上找到最高的 z-index。我正在使用这个

var getStyleProp = function(el, prop){
return window.getComputedStyle(el, null).getPropertyValue(prop);
}
var getHighestZIndex = function(){

var highestZIndex = 0,
HTMLElems = ["a","abbr","acronym","address","applet","area","article","audio","b","base","basefont","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","embed","fieldset","figcaption","figure","footer","form","frame","frameset","h1, h2, h3, h4, h5, h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","isindex","kbd","keygen","label","legend","li","link","listing","main","map","mark","menu","menuitem","meta","meter","nav","noembed","noscript","object","ol","optgroup","option","output","p","param","plaintext","pre","progress","q","rp","rt","rtc","ruby","s","samp","script","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","tt","u","ul","var","video","wbr","xmp"],
tags,
zIndex;

for (var i = 0; i < HTMLElems.length; i++){

tags = document.getElementsByTagName(HTMLElems[i]);

if (tags){
for (var c = 0; c < tags.length; c++){
zIndex =getStyleProp(tags[c], "z-index");
console.log(tags[c], "zIndex=", zIndex);
if (zIndex > highestZIndex){
highestZIndex = zIndex;
}

}
}


}

return highestZIndex;

}
console.log(getHighestZIndex());

但是一切都以“auto”的形式返回。 This ancient article解释了“bug”是如何导致这种行为的。我尝试克隆每个节点,将位置设置为相对位置,然后获取 z-index,

cl.style.display = "none";
cl.style.position = "absolute";
zIndex = (getStyleProp(cl, "z-index"));

但这也不起作用。这里有什么问题?有没有比重新创建页面上的所有内容更便宜的方法?

JSBIN

最佳答案

节点的克隆似乎没有获得 z-index,而节点本身返回正确的值。您可以尝试使用它(不确定它在包含大量内容的页面上会如何 react ):

var getHighestZIndex = function () {
var highestZIndex = 0,
zIndex,
pos,
tags = document.body.getElementsByTagName('*');

for (var c = 0; c < tags.length; c++) {
// Get the original 'position' property
pos = getComputedStyle(tags[c]).position;
// Set it temporarily to 'relative'
tags[c].style.position = "relative";
// Grab the z-index
zIndex = getComputedStyle(tags[c]).zIndex;
// Reset the 'position'
tags[c].style.position = pos;

console.log(tags[c], "zIndex=", zIndex);

if (zIndex > highestZIndex) { highestZIndex = zIndex; }
}

return highestZIndex;
};

console.log(getHighestZIndex());

JS Fiddle Demo

临时更改元素的位置可能会产生故障。您需要在包含大量内容和元素的页面上进行测试,这些内容和元素是 position:absolute;position:fixed;

关于javascript - 获取页面上每个元素的 Z-index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29175428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com