假设我有一个名为 sun 的矩形 div。
我的 div 有 4 种颜色。
颜色分别为红、绿、蓝、黄。
初始颜色为红色。
我想要的是当用户单击矩形时,矩形的颜色应从红色变为绿色。再次单击时,绿色变为蓝色,因此再次单击时,蓝色变为黄色,最后当用户再次单击时,颜色应从黄色变为红色,并且循环应继续。我无法实现这样的算法。
如果使用 if-else 树,我们将不胜感激(尽管不是必需的)。
像@Bravo评论一样,您可以使用javascript数组并使用eventListener添加
虽然很粗糙,但确实如此。
const box = document.querySelector('.box');
const listColor = ['red', 'green', 'blue', 'yellow'];
let currentColor = 1;
box.addEventListener('click', function() {
currentColor++;
this.style.backgroundColor = listColor[(currentColor % listColor.length)];
})
.box {
width: 100px;
height: 100px;
background-color: red;
transition: all .3s ease;
}
<div class="box"></div>
如果其他答案没有帮助,这就是我在评论中建议的内容
一个简单的数组和一个使用模运算符“包装”为 0 的数组索引
document.querySelector(".tgt").addEventListener(
"click",
((colours, index) =>
e => e.target.style.backgroundColor = colours[(index = (index + 1) % colours.length)]
)(["red", "green", "blue", "yellow"], 0)
);
<div class="tgt" style="background-color:red;height:64px;aspect-ratio:16/9">
</div>
额外好处 - 无需全局变量
你的问题有简单的解决方案,使用 js 数组和索引检查
// DOM Element
const SUN = document.getElementById("sun");
// Variables
let index = 0;
// Colors
const COLORS = ["red", "green", "blue", "yellow"];
// Handler
const initColor = () => {
SUN.style.backgroundColor = COLORS[index];
}
const changeColor = () => {
index++;
if (COLORS[index]) {
SUN.style.backgroundColor = COLORS[index];
}
}
// Event Listeners
window.addEventListener("DOMContentLoaded", initColor);
SUN.addEventListener("click", changeColor)
#sun {
width: 400px;
cursor: pointer;
height: 200px;
border: 1px solid black;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
</body>
<div id="sun">
</div>
<script src="./script.js"></script>
</html>