假設我有一個名為 sun 的矩形 div。
我有 4 種顏色的 div。
顏色分別為紅色、綠色、藍色和黃色。
初始顏色為紅色。
我想要的是當用戶點擊矩形時,矩形的顏色應該從紅色變為綠色。再次單擊時,綠色變為藍色,因此再次單擊時,藍色變為黃色,最后當用戶再次單擊時,顏色應從黃色變為紅色,并且回圈應繼續。我無法實作這樣的演算法。
如果使用 if-else 樹(盡管不是必需的),則表示贊賞。
uj5u.com熱心網友回復:
像@Bravo 評論一樣,您可以使用 javascript 陣列并使用 eventListener 添加
它粗糙但它。
const box = document.querySelector('.box');
const listColor = ['red', 'green', 'blue', 'yellow'];
let currentColor = 1;
box.addEventListener('click', function() {
this.style.backgroundColor = listColor[currentColor ];
if (currentColor == listColor.length) {
currentColor = 0;
}
})
.box {
width: 100px;
height: 100px;
background-color: red;
transition: all .3s ease;
}
<div class="box"></div>
uj5u.com熱心網友回復:
如果其他答案沒有幫助,這就是我在評論中的建議
一個簡單的陣列和一個使用模運算子“包裝”為 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>
額外的好處 - 不需要全域變數
uj5u.com熱心網友回復:
您的問題有 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/491747.html
標籤:javascript html css if 语句
上一篇:宣告具有相同鍵名的物件
