jquery 开关不变 css (3 种颜色)
jquery switch not changing css (3 colors)
您看到我需要在此代码中更改什么了吗?
<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 种颜色 toggleclass:
<button onclick="jQuery('.background').toggleClass('bgColor2')">toggle bg</button>
但我猜 toggleClass 只适用于 2 种颜色,而不是 3 种颜色 :(
您需要使用模运算符循环遍历 类。我制作了一个工作示例 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; }
您看到我需要在此代码中更改什么了吗?
<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 种颜色 toggleclass:
<button onclick="jQuery('.background').toggleClass('bgColor2')">toggle bg</button>
但我猜 toggleClass 只适用于 2 种颜色,而不是 3 种颜色 :(
您需要使用模运算符循环遍历 类。我制作了一个工作示例 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; }