【问题标题】:jquery switch not changing css (3 colors)jquery switch不改变css(3种颜色)
【发布时间】:2020-04-19 11:25:50
【问题描述】:

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

    <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 种颜色 :(

【问题讨论】:

  • 如此明确地removeClass()addClass().classNamejQuery 对象无关

标签: jquery css background-color classname


【解决方案1】:

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

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; }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-01
    • 2016-09-17
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    • 2018-03-23
    相关资源
    最近更新 更多