CSS/JavaScript: Make element top-most z-index/top-most modal element

◇◆丶佛笑我妖孽 提交于 2019-12-05 08:16:18

Here's how to do it :

var elements = document.getElementsByTagName("*");
var highest_index = 0;

for (var i = 0; i < elements.length - 1; i++) {
    if (parseInt(elements[i].style.zIndex) > highest_index) {
        highest_index = parseInt(elements[i].style.zIndex;
    }
}

highest_index now contains the highest z-index on the page... just add 1 to that value and apply it wherever you want. You can apply it like so :

your_element.style.zIndex = highest_index + 1;

Here's another way of achieving the same thing using jQuery :

var highest_index = 0;

$("[z-index]").each(function() {
    if ($(this).attr("z-index") > highest_index) {
         highest_index = $(this).attr("z-index");
    }
});

Again, same way to apply the new index to an element :

$("your_element").attr("z-index", highest_index + 1);

What about stacking context? It is not always true that: On a document highest z-index will be on top. See: http://philipwalton.com/articles/what-no-one-told-you-about-z-index/. If you do not take stacking context into account, setting a billion may not be enough to make your element on the top-most.

Sheavi's jQuery solution doesn't work because z-index is a css style, not an attribute.

Try this instead:

raiseToHighestZindex = function(elem) {
    var highest_index = 0;
    $("*").each(function() {
        var cur_zindex= $(this).css("z-index");
        if (cur_zindex > highest_index) {
            highest_index = cur_zindex;
            $(elem).css("z-index", cur_zindex + 1);
        }
    });
    return highest_index;
}; 

Return value may not be what you expect due to Javascript's async nature, but calling the function on any element will work fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!