如何实现点击元素时在预设颜色集合中循环切换元素颜色
点击循环切换div颜色实现方案
以下是符合要求的实现代码,优先采用if-else分支结构编写交互逻辑:
完整可运行代码
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>颜色切换Demo</title> <style> /* 给sun元素设置矩形基础样式,初始背景为红色 */ #sun { width: 200px; height: 150px; background-color: red; cursor: pointer; } </style> </head> <body> <div id="sun"></div> <script> // 获取目标div元素 const sun = document.getElementById('sun'); // 定义颜色状态标记:0=红色、1=绿色、2=蓝色、3=黄色,初始值0匹配默认红色 let currentColorStatus = 0; // 绑定点击事件 sun.addEventListener('click', function() { // 点击后状态值+1,切换到下一个颜色 currentColorStatus++; // 状态值超过3时重置为0,回到红色,实现循环 if (currentColorStatus > 3) { currentColorStatus = 0; } // 通过if-else分支匹配对应状态设置颜色 if (currentColorStatus === 0) { this.style.backgroundColor = 'red'; } else if (currentColorStatus === 1) { this.style.backgroundColor = 'green'; } else if (currentColorStatus === 2) { this.style.backgroundColor = 'blue'; } else { this.style.backgroundColor = 'yellow'; } }) </script> </body> </html>
逻辑说明
- 初始CSS直接给
#sun设置红色背景,和JS里的状态初始值对应,避免首次点击出现颜色错位 - 用数字类型的状态标记记录当前展示的颜色:0对应红色、1对应绿色、2对应蓝色、3对应黄色,初始值为0匹配默认红色
- 每次点击元素时先累加状态值,判断状态值超出3(即最后一个黄色的标记值)时直接重置为0,实现四色无限循环
- 颜色赋值环节完全使用if-else分支匹配对应状态设置背景色,逻辑直观易调试,后续调整颜色规则只需要修改分支判断和状态阈值即可
内容的提问来源于stack exchange,提问作者TJBro
相关产品推荐
相关产品推荐

