如何获取文档中 CSS z-index 最高的(元素)?

发布于 2024-10-08 09:23:58 字数 477 浏览 6 评论 0原文

这个问题再简单不过了。 z-index 值由 style=...className 指定,无论是否使用 Javascript。我认为这并不重要。如何(使用 Javascript)找到最高的 z-index? (它所使用的元素会很好,但不是必需的。)

您不能使用(新)querySelector,因为它不查询 CSS 值。有什么办法可以查询CSS吗? (不是样式表,而是实际使用的值。)

Grazi


获取前 5 个元素 + z 索引:

Array.from(document.querySelectorAll('*')).map(el => [el, getComputedStyle(el).zIndex]).filter(v => !isNaN(parseInt(v[1]))).sort((a, b) => b[1] - a[1]).slice(0, 5)

The question couldn't be easier. The z-index values are assigned by style=... or className, with Javascript or not. I don't think it matters. How do I find (with Javascript) the highest z-index? (The element it's used in would be nice, but not necessary.)

You can't use the (new) querySelector, because it doesn't query CSS values. Is there someway to query CSS? (Not the stylesheets, but the actual used values.)

Grazi


Get top 5 elements + z-indexes:

Array.from(document.querySelectorAll('*')).map(el => [el, getComputedStyle(el).zIndex]).filter(v => !isNaN(parseInt(v[1]))).sort((a, b) => b[1] - a[1]).slice(0, 5)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

月下客 2024-10-15 09:23:58

这并不像查找 z-index 最高的元素那么简单。堆叠顺序还取决于树关系,因此,如果显式设置了具有最多 z-index 的静态定位元素,并且如果您的代码检索了该元素,则它将毫无用处,因为 z-index 对于静态定位元素是无用的。

此外,IE 的堆叠顺序规则完全被破坏,因此您也必须考虑到这一点。您可能需要考虑 IE 8/9 之前版本中的 iframe/select 元素,因为它们比任何其他节点具有更高的堆叠顺序优先级。

这可能会有用: http://www.w3.org/TR/CSS21/zindex .html

您必须遵循所有这些内容并考虑 IE 错误,以便采用一致的方法来获取具有最高堆叠顺序优先级的元素。

It's not as simple as finding the element with the highest z-index. Stacking order also depends on tree relationship, so if a static positioned element with the most z-index explicitly set, and if your code retrieved that, it would be useless since z-index is useless on static positioned elements.

In addition, IE's stacking order rules are completely broken so you would have to account for that as well. And you may have to account for iframe/select elements in IE pre 8/9 since they have more stacking order priority than any other nodes.

This would probably be useful: http://www.w3.org/TR/CSS21/zindex.html

You'd have to follow all of those and account for IE bugs in order to have a consistent method of getting the element with the most stacking order priority.

べ繥欢鉨o。 2024-10-15 09:23:58

这是 kennebec/Pravens 代码的修改版本,用于查找堆叠上下文中的最高 z 索引。此版本还考虑了不透明度。

如果您想要的只是将一个元素放置在页面中其他所有元素的顶部,只需调用 highZ(document.body) 或仅调用 highZ() 即可。它会找到根堆叠上下文的最高 z 索引,这将完全做到这一点。

  • 只有非静态定位的元素在堆叠上下文中才重要。
  • 未定位的元素不会启动新的堆叠上下文。因此它们的后代可能存在于当前的堆叠上下文中。因此就有了递归。
  • 此外,如果 z-index 为“auto”,则该元素不会启动新的堆叠上下文,因此您必须递归遍历其元素。
  • 不透明度值小于 1 的元素会启动一个新的堆叠上下文。如果未定位不透明度小于 1 的元素,则实现必须在其父堆叠上下文中以与“z-index: 0”的定位元素相同的堆叠顺序绘制它创建的图层,并且'不透明度:1'。如果定位不透明度小于 1 的元素,则按照 [CSS21] 中的描述应用“z-index”属性,但“auto”被视为“0”,因为始终会创建新的堆叠上下文。

    函数 highZ(父级,限制){
        极限=极限||无穷大;
        父=父||文档.正文;
        var who, temp, max= 1, 不透明度, i= 0;
        var Children = Parent.childNodes, length = Children.length;
        while(i<长度){
            谁=孩子们[i++];
            if (who.nodeType != 1) 继续; // 仅限元素节点
            不透明度 = deepCss(who,"不透明度");
            if (deepCss(who,"位置") !== "静态") {
                temp = deepCss(who,"z-index");
                if (temp == "auto") { // 定位且 z-index 为 auto,不透明度 < 的新堆栈上下文0. 此外,当 zindex 为 auto 时,在堆栈上下文中应将其视为 zindex = 0。
                    (不透明度<1)? temp=0:temp = highZ(谁);
                } 别的 {
                    temp = parseInt(temp, 10) || 0;
                }
            } else { // 非定位元素,一个新的不透明度堆叠上下文< 1 和 zindex 应被视为 0
                (不透明度<1)? temp=0:temp = highZ(谁);
            }
            if (temp > max && temp <= limit) max = temp;                
        }
        返回最大值;
    }
    
    函数 deepCss(who, css) {
        var sty, val, dv= document.defaultView ||窗户;
        if (who.nodeType == 1) {
            sty = css.replace(/\-([az])/g, 函数(a, b){
                返回 b.toUpperCase();
            });
            val = who.style[sty];
            如果(!val){
                if(who.currentStyle) val= who.currentStyle[sty];
                否则如果(dv.getCompulatedStyle){
                    val= dv.getCompulatedStyle(who,"").getPropertyValue(css);
                }
            }
        }
        返回值|| “”;
    }
    

This is a modified version of kennebec's/Pravens code which finds the highest z-index within a stacking context. This version also takes opacity into account.

If all you're looking for is to position an element on top of everything else in the page, simply call highZ(document.body) or just highZ(). It finds the highest z-index of the root stacking context which will do exactly that.

  • Only non-statically positioned elements matter within a stacking context.
  • Elements that are not positioned do not start a new stacking context. So their descendents may exist in the current stacking context. Hence the recursion.
  • Also, if the z-index is 'auto', the element does not start a new stacking context, so you must recurse through its elements.
  • elements with an opacity value less than 1 start a new stacking context. If an element with opacity less than 1 is not positioned, implementations must paint the layer it creates, within its parent stacking context, at the same stacking order that would be used if it were a positioned element with ‘z-index: 0’ and ‘opacity: 1’. If an element with opacity less than 1 is positioned, the ‘z-index’ property applies as described in [CSS21], except that ‘auto’ is treated as ‘0’ since a new stacking context is always created.

    function highZ(parent, limit){
        limit = limit || Infinity;
        parent = parent || document.body;
        var who, temp, max= 1, opacity, i= 0;
        var children = parent.childNodes, length = children.length;
        while(i<length){
            who = children[i++];
            if (who.nodeType != 1) continue; // element nodes only
            opacity = deepCss(who,"opacity");
            if (deepCss(who,"position") !== "static") {
                temp = deepCss(who,"z-index");
                if (temp == "auto") { // positioned and z-index is auto, a new stacking context for opacity < 0. Further When zindex is auto ,it shall be treated as zindex = 0 within stacking context.
                    (opacity < 1)? temp=0:temp = highZ(who);
                } else {
                    temp = parseInt(temp, 10) || 0;
                }
            } else { // non-positioned element, a new stacking context for opacity < 1 and zindex shall be treated as if 0
                (opacity < 1)? temp=0:temp = highZ(who);
            }
            if (temp > max && temp <= limit) max = temp;                
        }
        return max;
    }
    
    function deepCss(who, css) {
        var sty, val, dv= document.defaultView || window;
        if (who.nodeType == 1) {
            sty = css.replace(/\-([a-z])/g, function(a, b){
                return b.toUpperCase();
            });
            val = who.style[sty];
            if (!val) {
                if(who.currentStyle) val= who.currentStyle[sty];
                else if (dv.getComputedStyle) {
                    val= dv.getComputedStyle(who,"").getPropertyValue(css);
                }
            }
        }
        return val || "";
    }
    
好菇凉咱不稀罕他 2024-10-15 09:23:58

您需要循环遍历 DOM 中的每个元素,并跟踪循环时找到的最大 z 索引以及具有该 z 索引的元素。然后,完成后,您将获得您正在寻找的元素。

这是一段非常密集的脚本,可能会杀死用户的浏览器。你究竟为什么要这样做?

You would need to loop through every single element in the DOM and keep track of the max z-index found as you loop, along with the element that has that z-index. Then, when you are done, you will have the element you are looking for.

This is an incredibly intensive piece of script and could kill your users' browsers. Why in the world would you want to do this?

谈场末日恋爱 2024-10-15 09:23:58

您只需要同级元素即可找到最高的 z-index,因此从父元素或主体开始。

通常,您有一些 z-index 非常高的元素,您希望它始终位于顶部 - 如果是这样,
忽略超过 100 万的 z 索引或安全高于同级数量的任何值。

您可以在一个函数中完成此操作,但查找样式表值的语法很方便。

function highZ(pa, limit){
    limit= limit || Infinity;
    pa= pa || document.body;
    var who, tem, mx= 1, A= [], i= 0, L;
    pa= pa.childNodes, L= pa.length;
    while(i<L){
        who= pa[i++]
        if(who.nodeType== 1){
            tem= parseInt(deepCss(who,"z-index")) || 0;
            if(tem> mx && tem<=limit) mx= tem;
        }
    }
    return mx;
}
function deepCss(who, css){
    var sty, val, dv= document.defaultView || window;
    if(who.nodeType== 1){
        sty= css.replace(/\-([a-z])/g, function(a, b){
            return b.toUpperCase();
        });
        val= who.style[sty];
        if(!val){
            if(who.currentStyle) val= who.currentStyle[sty];
            else if(dv.getComputedStyle){
                val= dv.getComputedStyle(who,"").getPropertyValue(css);
            }
        }
    }
    return val || "";
}

警报(高Z())

You only need sibling elements to find the highest z-index, so start with a parent element or the body.

And often you have some element with a really high z-index that you want to be always on top- if so,
ignore z indexes over a million or whatever is safely above the number of siblings.

You can do it in one function, but the syntax for finding stylesheet values is handy to have around.

function highZ(pa, limit){
    limit= limit || Infinity;
    pa= pa || document.body;
    var who, tem, mx= 1, A= [], i= 0, L;
    pa= pa.childNodes, L= pa.length;
    while(i<L){
        who= pa[i++]
        if(who.nodeType== 1){
            tem= parseInt(deepCss(who,"z-index")) || 0;
            if(tem> mx && tem<=limit) mx= tem;
        }
    }
    return mx;
}
function deepCss(who, css){
    var sty, val, dv= document.defaultView || window;
    if(who.nodeType== 1){
        sty= css.replace(/\-([a-z])/g, function(a, b){
            return b.toUpperCase();
        });
        val= who.style[sty];
        if(!val){
            if(who.currentStyle) val= who.currentStyle[sty];
            else if(dv.getComputedStyle){
                val= dv.getComputedStyle(who,"").getPropertyValue(css);
            }
        }
    }
    return val || "";
}

alert(highZ())

嘿咻 2024-10-15 09:23:58

meder 提出了一个很好的观点!无论如何,我尝试对其进行编码,因为我在工作中感到无聊并且无法帮助自己:

注意:仅适用于使用 style 属性设置的样式(不会捕获样式表设置的样式)

function getHighIndex (selector) {
    if (!selector) { selector = "*" };

    var elements = document.querySelectorAll(selector) ||
                   oXmlDom.documentElement.selectNodes(selector),
        i = 0,
        e, s,
        max = elements.length,
        found = [];

    for (; i < max; i += 1) {
        e = elements[i].style.zIndex;
        s = elements[i].style.position;
        if (e && s !== "static") {
          found.push(parseInt(e, 10));
        }
    }

    return found.length ? Math.max.apply(null, found) : 0;
}

meder makes a great point! I tried to code it anyway, because I'm bored at work and can't help myself:

NOTE: Will only work on style set using the style attribute (won't capture style set by stylesheets)

function getHighIndex (selector) {
    if (!selector) { selector = "*" };

    var elements = document.querySelectorAll(selector) ||
                   oXmlDom.documentElement.selectNodes(selector),
        i = 0,
        e, s,
        max = elements.length,
        found = [];

    for (; i < max; i += 1) {
        e = elements[i].style.zIndex;
        s = elements[i].style.position;
        if (e && s !== "static") {
          found.push(parseInt(e, 10));
        }
    }

    return found.length ? Math.max.apply(null, found) : 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文