通过DOM上的多个元素旋转多个类

时间:2017-05-22 18:36:41

标签: jquery

当我点击按钮时,类会在每个div中向上或向下旋转。到目前为止,我所能做的就是旋转类,但它只旋转相同div的类。



 

var classes = ['a', 'b', 'c'];  // the different classes to rotate through each div




$('div').each(function() {     // the div needs to rotate classes over and over
    var i = 0;
    
    $('button').click(function() {
        $('div').removeClass( classes[ i ] );
        i = ++i % classes.length;            
        $('div').addClass( classes[ i ] );
    });
});

div { color:white; margin: 4px; width: 100px; height: 100px; }
.a {
    background-color: blue;
}

.b {
    background-color: red;
}

.c {
    background-color: green;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div class="a"></div>  //class change on click to b, than c, back to a..
<div class="b"></div>  //this change to c than a than b ..
<div class="c"></div> // basically these classes always rotate

<button>
rotate
</button>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

  1. 首先在体外初始化变量并在内部声明 记录准备部分,以便它不会再次重新初始化。
  2. 移动数组,然后添加/删除类。
  3. var  classes ;
    $(document).ready(function() {
     classes = ['a', 'b', 'c'];
    });
    
       
        $('button').click(function() {
        debugger;
        var i = 0;
         var remove = classes.shift();
          classes.push(remove)
        $('div').each(function(key) { 
       
        $(this).removeClass()
        
        $(this).addClass(classes[i]);
          i++;
          
        });
    });
    div { color:white; margin: 4px; width: 100px; height: 100px; }
    .a {
        background-color: blue;
    }
    
    .b {
        background-color: red;
    }
    
    .c {
        background-color: green;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
    <div class="a"></div>  //class change on click to b, than c, back to a..
    <div class="b"></div>  //this change to c than a than b ..
    <div class="c"></div> // basically these classes always rotate
    
    <button>
    rotate
    </button>