jquery - 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 种颜色 :(
解决方案
您需要使用模运算符循环遍历您的类。我在这里制作了一个工作示例
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; }
推荐阅读
- r - 缺少参数“no”,没有默认值
- wordpress - 当产品保存在 WooCommerce 后端时,以编程方式为库存状态分配标签
- flutter-getx - 在渲染之前更新 getx 控制器中的值
- excel - 有没有办法自动扩展数据透视表的数据透视表范围?
- node.js - updateOne() 找到匹配项后从 MongoDB 获取现有文档的 _id?节点.js
- python - 结合 Spark Data Frames 实现代码的更有效方式
- selenium - Selenium WebDriver 中的列表框向上或向下滚动
- javascript - 显示来自 Swapi API 但接收 [object Promise] 的电影
- javascript - 按作为字符串日期的键对对象键值对进行排序
- javascript - 我有一个带有图标和文本的按钮,我尝试将它们分组,这样图标就不能单独点击