背景
winter重学前端课程中的一个问题:如何用JS实现红绿灯?
- codepen在线演示:https://codepen.io/ytxka/pen/mNzgMB
-
效果预览:
image.png
实现步骤:
- 静态页面绘制
- 实现改变颜色的函数
changeColor
- 实现延时函数
sleep
- 增加倒计时函数
countDown
源码
- HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>红绿灯</title>
<link rel="stylesheet" href="./static/common.css">
</head>
<body>
<div class="main-wrap">
<div class="traffic-light-wrap">
<ul id="lights">
<li id="red"></li>
<li id="yellow"></li>
<li id="green"></li>
</ul>
</div>
</div>
<script src="./static/index.js"></script>
</body>
</html>
- CSS
.traffic-light-wrap {
width: 300px;
height: 100px;
padding: 1%;
box-sizing: border-box;
box-shadow: 5px 5px 10px rgb(180, 179, 179);
}
ul {
display: flex;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
justify-content: space-around;
list-style: none;
}
li {
width: 80px;
height: 80px;
font-size: 18px;
font-weight: 800;
text-align: center;
color: #fff;
line-height: 80px;
border-radius: 50%;
background: #eee;
}
- JS
var lights = document.getElementById('lights');
var red = document.getElementById('red');
var yellow = document.getElementById('yellow');
var green = document.getElementById('green');
const COLOR_OFF = '#eee';
// 延时
function sleep(wait) {
return new Promise((resolve, reject) => {
setTimeout(resolve, wait);
});
}
function initColor(light) {
light.style.background = COLOR_OFF;
}
// 倒计时
function countDown(ele, time) {
clearInterval(this.timer);
let second = time - 1;
this.timer = setInterval(() => {
ele.innerHTML = second;
second -= 1;
if(second < 0) {
ele.innerHTML = '';
clearInterval(this.timer);
}
}, 1000);
}
// 改变某个灯的颜色,并重置其他灯的背景色(async函数返回一个promise对象)
async function changeColor(light, color, duration) {
light.style.background = color;
countDown(light, duration / 1000);
await sleep(duration);
initColor(light);
}
async function lunchTrafficLight() {
while(true) {
// changeColor函数返回的是一个promise对象,因此需要await
await changeColor(red, '#e85a5a', 5000);
await changeColor(yellow, '#f7bc69', 3000);
await changeColor(green, '#61b54a', 5000);
}
}
lunchTrafficLight();