首页 > 解决方案 > jquery switch不改变css(3种颜色)

问题描述

你看到我需要在这段代码中改变什么了吗?

    <style>
    .bgColor1{background: red !important;}
    .bgColor2{background: blue !important;}
    .bgColor3{background: green !important;}
    </style>

    <button onclick="mySwitch()">SWITCH COLOR</button>
    <script>
    function mySwitch() {
       jQuery('.background').each(function(){
       var classes = ['bgColor1','bgColor2','bgColor3'];
       jQuery('.background').className = classes[($.inArray(jQuery('.background').className, classes)+1)%classes.length];
      });
    });
  </script>

以下仅适用于 2 种颜色的切换类:

    <button onclick="jQuery('.background').toggleClass('bgColor2')">toggle bg</button>

但我猜一个 toggleClass 只适用于 2 种颜色,而不是 3 种颜色 :(

标签: jquerycssbackground-colorclassname

解决方案


您需要使用模运算符循环遍历您的类。我在这里制作了一个工作示例

HTML:

<div id="background" class="bgColor0">
  <button id="but">SWITCH COLOR</button>
</div>

JavaScript:

let counter = 0;
$('#but').click(function () {

  $('#background').removeClass('bgColor' + ((counter % 3))); // Remove the previous color's class
  $('#background').addClass('bgColor' + ((counter + 1) % 3)); // Add the new colors class

  counter++;

});

CSS:

#background {
  width: 200px;
  height: 200px;
}

.bgColor0{ background: red !important; }
.bgColor1{ background: blue !important; }
.bgColor2{ background: green !important; }

推荐阅读