简体   繁体   English

获取页面上每个元素的Z索引

[英]Get Z-index of each element on the page

I am trying to find the highest z-index on a page. 我正在尝试在页面上找到最高的z-index。 I am using this 我正在用这个

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());

But everything is coming back as "auto" . 但是一切都回到了"auto" This ancient article explains how a "bug" is causing this behavior. 这篇古老的文章解释了“错误”是如何导致此行为的。 I've tried to make clones of each node, set the position to relative, and then get the z-index, 我尝试制作每个节点的克隆,将位置设置为相对,然后获取z-index,

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

but that is not working either. 但这也不起作用。 What is wrong here? 怎么了 Is there a cheaper way to do this than recreating everything on the page? 有比重新创建页面上的所有内容便宜的方法吗?

JSBIN 吉宾

The node's clone does not seem to get the z-index, while the node itself returns the right value. 节点的克隆似乎没有获得z索引,而节点本身返回了正确的值。 You could try using it instead (not sure how it might react on a page with lots of content): 您可以尝试使用它(不知道它在包含大量内容的页面上可能有什么反应):

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 JS小提琴演示

Changing the element's position temporarily might produce a glitch. 临时更改元素的位置可能会产生故障。 You'll need to test that on a page with lots of contents and elements that are position:absolute; 您需要在页面上包含很多position:absolute;和内容的元素上进行测试position:absolute; or position:fixed; position:fixed; .

If this doesn't fit your use-case, just let me know, and I'll remove it. 如果这不适合您的用例,请告诉我,我将其删除。 However, as a thought. 但是,作为一种思想。

Can you loop through all the tags, and if the value is "auto" assume it's 999. If it's >= 1000, take that as your "highest" value. 您能否遍历所有标记,并且如果值是“ auto”,则假定它是999。如果值> = 1000,则将其作为“最高”值。 Then, increment your zIndex up from your highest number that way. 然后,以这种方式将zIndex从最高编号增加到最高。 This way, the first tag you place will be 1000, the next will be 1001. 这样,您放置的第一个标签将是1000,下一个将是1001。

var elements  = document.getElementsByTagName("*"),
    maxZIndex = 999;

for( var i=0; i < elements.length; i++ ) {
    var zIndex = parseInt(elements[0].style.zIndex) || 999;
    maxZIndex  = zIndex > maxZIndex ? zIndex : maxZIndex;
}
return maxZIndex;

This would fit a use case where you are just trying to make sure that the tag you are placing is greater than anything on the page...such as placing a modal. 这将适合一个用例,您只需要确保要放置的标签大于页面上的任何内容(例如放置模式)即可。

999 is overkill...somewhat of a "just in case" I missed something because anything with z-index:auto is equivalent to zero. 999是过大的...有点“以防万一”,我错过了一些东西,因为z-index:auto的值等于零。 See the following "proof" where even though my z-index is only "1" it overlaps boxes that are 3-deep of "auto". 请参阅以下“证明”,即使我的z-index仅为“ 1”,它也会与“ auto”的3层深度的框重叠。

<div style='position:absolute;background-color:white;z-index:1;width:94px;height:94px;'>

</div>
<div style='position:absolute;background-color:red;width:100px;height:100px;'>
    <div style='position:absolute;background-color:blue;width:98px;height:98px;'>
        <div style='position:absolute;background-color:green;width:96px;height:96px;'>

        </div>
    </div>
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM