gpt4 book ai didi

javascript - 如何根据最高z-index获取元素属性

转载 作者:行者123 更新时间:2023-11-28 12:59:56 29 4
gpt4 key购买 nike

我不知道如何实现这一点,我有一些带有 common_class 类名的元素,我想获取最高 z-index 元素的 ID,这可能吗?

function findHighestZIndex(elem)
{
var elems = document.getElementsByClassName(elem);
var highest = 0;
for (var i = 0; i < elems.length; i++)
{
var id = document.getElementsByClassName(elem);
id.getAttribute("id");
console.log(id);
var zindex=document.defaultView.getComputedStyle(elems[i],null).getPropertyValue("z-index");
var ElementDisplay = document.defaultView.getComputedStyle(elems[i],null).getPropertyValue("display");
if ((zindex > highest) && (zindex != 'auto') && (ElementDisplay == 'block'))
{
highest = zindex;
}

}

最佳答案

这是 getHighest(selector) 函数的简短有效实现,以及使用此函数检索 id 值的示例代码段(单击框以递增他们的 z 索引)。

(重要部分是前三个函数;如果需要,可以将它们压缩为一个函数。)

function getHighest(selector) {
// Return the element that matches selector having the largest z index
return Array.from(document.querySelectorAll(selector)).reduce((a, b) => getZIndex(a) >= getZIndex(b) ? a : b);
}

function getZIndex(el) {
// Return the z-index of el, or 0 if none is set.
return parseInt(getCssProperty(el, "z-index")) || 0;
}

function getCssProperty(el, prop) {
// Return the computed value of the css property prop for the element el
return document.defaultView.getComputedStyle(el, null).getPropertyValue(prop);
}


// -------------------------------------------------------------------------
// additional code for demo below
// -------------------------------------------------------------------------


function updateHighest() {
let highest = getHighest(".box");
document.querySelector("#highest").textContent = `#${highest.id} (${getZIndex(highest)})`;
document.querySelector("#highest").style.color = getCssProperty(highest, "background-color");
}

function setContentToZIndex(el) {
el.textContent = getZIndex(el);
}

Array.from(document.querySelectorAll(".box")).forEach(b => {
b.onclick = () => {
b.style.zIndex = getZIndex(b) + 1;
setContentToZIndex(b);
updateHighest();
};
setContentToZIndex(b);
updateHighest();
});
.box {
width: 100px;
height: 100px;
display: block;
background: grey;
position: absolute;
color: white;
font-size: 2rem;
text-align: center;
line-height: 100px;
user-select: none;
font-family: sans-serif;
}

#b1 {
background: #ff268a;
left: 0px;
top: 0px;
}

#b2 {
background: #242792;
left: 50px;
top: 50px;
}

#b3 {
background: #0ac3d6;
left: 25px;
top: 75px;
}

p {
margin-left: 200px;
font-family: sans-serif;
font-size: 1.2rem;
}
<div class="box" id="b1"></div>

<div class="box" id="b2"></div>

<div class="box" id="b3"></div>

<p>highest z-index: <span id="highest"></span></p>

关于javascript - 如何根据最高z-index获取元素属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51601136/

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