How to find the highest z-index using jQuery

后端 未结 11 1140
终归单人心
终归单人心 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

    Here is a very concise method:

    var getMaxZ = function(selector){
        return Math.max.apply(null, $(selector).map(function(){
            var z;
            return isNaN(z = parseInt($(this).css("z-index"), 10)) ? 0 : z;
        }));
    };
    

    Usage:

    getMaxZ($("#layer-1,#layer-2,#layer-3,#layer-4"));
    

    Or, as a jQuery extension:

    jQuery.fn.extend({
        getMaxZ : function(){
            return Math.max.apply(null, jQuery(this).map(function(){
                var z;
                return isNaN(z = parseInt(jQuery(this).css("z-index"), 10)) ? 0 : z;
            }));
        }
    });
    

    Usage:

    $("#layer-1,#layer-2,#layer-3,#layer-4").getMaxZ();
    

提交回复
热议问题