How to find the highest z-index using jQuery

后端 未结 11 1082
终归单人心
终归单人心 2020-11-28 07:42

I have a number of div elements with different z-index. And I want to find the highest z-index among these divs - how can I achieve it?

CSS:

#layer-1         


        
11条回答
  •  有刺的猬
    2020-11-28 08:44

    Vanilla JS, not 100% cross-browser. Including as reference for future readers/alternative method.

    function getHighIndex (selector) {
        // No granularity by default; look at everything
        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 = window.getComputedStyle(elements[i], null).zIndex || elements[i].currentStyle.zIndex;
            s = window.getComputedStyle(elements[i], null).position || elements[i].currentStyle.position;
    
            // Statically positioned elements are not affected by zIndex
            if (e && s !== "static") {
              found.push(parseInt(e, 10));
            }
        }
    
        return found.length ? Math.max.apply(null, found) : 0;
    }
    

提交回复
热议问题