交通灯
分析:每隔一秒就会变另外一个灯,红黄蓝交换显示,灯是用背景颜色控制,每个一秒转变一次考虑用定时器setInterval(),当第一个灯亮起红灯,黄蓝灯就熄灭,当黄灯亮起,红蓝灯就熄灭,当蓝灯亮起,红黄灯就熄灭,代码如下:
<!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>
<style>
div {
width: 100px;
height: 100px;
border: 1px solid #000;
border-radius: 50%;
background-color: rgb(241, 245, 245);
box-shadow: 0 0 3px 1px inset;
}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
<script>
let div = document.querySelectorAll("div")
//声明变量num,用来记录定时器执行时该亮什么灯
let num = 1
setInterval(() => {
if (num == 1) {
div[0].style.backgroundColor = "red"
div[2].style.backgroundColor = "#fff"
num = 2
} else if (num == 2) {
div[0].style.backgroundColor = "#fff"
div[1].style.backgroundColor = "yellow"
num = 3
} else {
div[2].style.backgroundColor = "green"
div[1].style.backgroundColor = "#fff"
num = 1
}
}, 1000)
</body>
</html>