實現的效果:點選時變換顏色,顏色的順序:red -> green -> yellow -> red
1、基本結構
<div id="box" style="background: red;"></div>
<style>
* {
margin: 0;
padding: 0;
}
#box {
width: 200px;
height: 200px;
margin: 20px auto;
}
</style>
複製程式碼
2、js實現效果
獲得要操作的物件
var box = document.getElementById("box");
複製程式碼
2.1 if else實現
box.onclick = function () {
let item = box.style.background;
if (item == "red") {
box.style.background = "green";
} else if (item == "green") {
box.style.background = "yellow";
} else {
box.style.background = "red";
}
}
複製程式碼
2.2 switch case 實現
box.onclick = function () {
let item = box.style.background;
switch (item) {
case 'red':
box.style.background = "green";
break;
case 'green':
box.style.background = "yellow";
break;
default:
box.style.background = 'red';
}
}
複製程式碼