用JS动态设置z-index

时间:2013-10-17 01:23:03

标签: javascript jquery dom-manipulation

我想在点击图标时更改z-index-每次用户点击图标时,index-z为+1,但我的代码不起作用:

  $(document).on('click', '.icon-layer-up', function() { 
      console.log($(this).parent(".ui-wrapper").css("z-index"));
      var currentIndex = $(this).parent(".ui-wrapper").css("z-index"); 
      if ( currentIndex = "auto" ) {
        currentIndex = 0;
      }
      var num = currentIndex++;
       $(this).parent(".ui-wrapper").css("z-index", num );
    });

3 个答案:

答案 0 :(得分:2)

之间存在很大差异
if( currentIndex = "auto" ) {

if( currentIndex == "auto") {

第一个执行你不想要的赋值,总是返回“auto”作为结果,if语句总是运行,将currentIndex重置为0.

404也是正确的,在这种情况下你不希望我们“num ++”有两个原因

  1. 它只会在赋值后尝试递增值,这会给你一个不正确的值,但是......
  2. 在您的情况下,“num”实际上是字符串,因为它是如何被获取的。您需要将其转换为要添加的数字:parseInt(num) + 1

答案 1 :(得分:1)

您的问题是var num = currentIndex++;

currentIndex++会将currentIndex增加到currentIndex + 1,但会返回原始值,因此会将num分配给原始值currentIndex。只需使用var num = currentIndex + 1即可。

使用++并不是很好的编码习惯,如果您只想添加1.如果您只是添加,请使用+ 1

答案 2 :(得分:1)

我注意到您的代码中的第一件事,可能是也可能不是问题,是您缺少jQuery on事件的数据参数。您还希望将活动应用于document.body而不是document

$(document.body/*changed*/).on('click', '.icon-layer-up', {}/*added*/, function() {

接下来,您始终将currentIndex设置为auto,然后设置为0,而不是检查它是否等于auto

if ( currentIndex ==/*fixed*/ "auto" ) {

此外,您最初将currentIndex设置为字符串,只会将字符串转换为数字,当您尝试按照您的方式递增它时。您必须先尝试将其转换为Number,然后检查以确保它是Number然后将其递增。

所以固定代码应该是:

  $(document.body).on('click', '.icon-layer-up', {}, function() { 
      console.log($(this).parent(".ui-wrapper").css("z-index"));
      var currentIndex = Number($(this).parent(".ui-wrapper").css("z-index")); 
      if ( isNaN(currentIndex) ) { // if is not a number, set it to 0
        currentIndex = 0;
      }
      var num = currentIndex++;
       $(this).parent(".ui-wrapper").css("z-index", num );
    });

接下来,请务必阅读z-index,了解其工作原理。 z-index不会应用于position的默认static元素。尝试将元素设置为position: relative;,您尝试应用z-index

z-index的参考文献:
Understanding CSS z-index
Adding z-index

相关问题