【问题标题】:How to get the highest z-index value of several div have same name? [duplicate]如何获得多个具有相同名称的 div 的最高 z-index 值? [复制]
【发布时间】:2019-01-21 02:24:52
【问题描述】:

可能重复:
Select DIV with highest z-index

如何获得最高的 z-index 值?
将所有 div z-index 值放入数组并使用 math.max?或者有什么建议?

<div class="a" z-index="1">
<div class="a" z-index="3">
<div class="a" z-index="4">
<div class="a" z-index="5">
<div class="a" z-index="6">
<div class="a" z-index="11">...

<div class="b" z-index="//top+1">

js

var top = // highest z-index value;

【问题讨论】:

  • 将所有 div 的 z-index 值放入数组并使用math.max :P,那很好!

标签: javascript jquery


【解决方案1】:

你可以这样做:

var zIndx = [];
$("div.a").each(function() {
    zIndx.push( $(this).attr("z-index") );
});
console.log( Math.max.apply( Math, zIndx ) );

【讨论】:

    【解决方案2】:
    var maxValue = Math.max.apply( Math, $('.a').map(function() {
        return +$.attr(this, 'z-index');
    }));
    

    这是小提琴:http://jsfiddle.net/ZFhzu/


    如果您使用的是现代 JavaScript,则不需要花哨的 apply。您可以改为传播值:

    let maxValue = Math.max(...$('.a').get().map(el => +$.attr(el, 'z-index')));
    

    这是小提琴:http://jsfiddle.net/7y3sxgbk/

    【讨论】:

    • 你能解释一下代码吗?
    • .map() 函数接受一个函数,该函数将为 jQuery 集合中的每个元素调用,返回一个包含该函数返回的所有值的新数组。 .apply() 函数允许您将一堆参数作为数组传递给底层函数。
    【解决方案3】:

    JavaScript 的Array.reduce 可以完成这项工作。 .get 可以得到你需要的数组:

    var top = $(".a").get().reduce(function (a, b) {
       return Math.max(typeof a === 'object' && $(a).attr('z-index') || a,
          $(b).attr('z-index'));
    });
    

    http://jsfiddle.net/8jpea/1/

    顺便说一句,在使用自己的自定义属性时要小心。如果可以,请使用data-z-index

    【讨论】:

      【解决方案4】:

      这是您可以使用的功能。

      var index_highest = 0;   
      
      // more effective to have a class for the div you want to search and 
      // pass that to your selector
      
      $(".a").each(function() {
      
               // always use a radix when using parseInt
      
               var index_current = parseInt($(this).css("zIndex"), 10);
      
               if(index_current > index_highest) {
                     index_highest = index_current;
                }
      });
      
      console.log(index_highest);
      

      【讨论】:

        【解决方案5】:
            var top = 0;
            $('.a').each(function(){
                if(top < parseInt($(this).attr('z-index'))){
                    top= parseInt($(this).attr('z-index'));
                }
            });
            $('.b').attr('z-index',top+1);
        

        jsfiddle.net/EC36x

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-11-03
          • 1970-01-01
          • 2010-10-13
          • 2013-01-03
          • 1970-01-01
          • 2015-07-08
          相关资源
          最近更新 更多