您看到我需要在此代码中进行哪些更改? 以下仅适用于2种颜色的切换类别: 但是我猜到toggleClass只支持2种颜色,而不是3种:( 答案 0 :(得分:1) 您需要使用模运算符在类中循环。我已经制作了一个有效的示例here HTML: JavaScript: CSS: <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>
<button onclick="jQuery('.background').toggleClass('bgColor2')">toggle bg</button>
1 个答案:
<div id="background" class="bgColor0">
<button id="but">SWITCH COLOR</button>
</div>
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++;
});
#background {
width: 200px;
height: 200px;
}
.bgColor0{ background: red !important; }
.bgColor1{ background: blue !important; }
.bgColor2{ background: green !important; }