forked from dunizb/CodeTest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathred-yellow-green.html
More file actions
95 lines (92 loc) · 3.02 KB
/
red-yellow-green.html
File metadata and controls
95 lines (92 loc) · 3.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<!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>
<style>
#traffic-light {
width: 50px;
height: 50px;
border-radius: 50%;
border: 1px solid #000;
}
.traffic-box {
display: flex;
flex-direction: column;
}
.traffic {
width: 50px;
height: 50px;
margin: 5px 0;
border-radius: 50%;
border: 1px solid #000;
}
.red { background-color: red;}
.yellow { background-color: yellow;}
.green { background-color: green;}
</style>
</head>
<body>
<header>
<h1>实现一个红绿灯,把一个圆形 div 按照绿色 3 秒,黄色 1 秒,红色 2 秒循环改变背景色</h1>
<p>Promise、async\await 语法实现</p>
</header>
<div id="traffic-light"></div>
<hr/>
<div class="traffic-box">
<div id="traffic-red" class="traffic"></div>
<div id="traffic-yellow" class="traffic"></div>
<div id="traffic-green" class="traffic"></div>
</div>
<script>
function sleep(duration) {
return new Promise(function(reslove){
setTimeout(reslove, duration);
})
}
async function changeColor(duration, color) {
document.getElementById("traffic-light").style.background = color;
await sleep(duration);
}
async function main(){
while(true){
await changeColor(3000,"green");
await changeColor(1000, "yellow");
await changeColor(2000, "red");
}
}
main()
//***************************************************************
var red = document.getElementById('traffic-red')
var yellow = document.getElementById('traffic-yellow')
var green = document.getElementById('traffic-green')
async function changeColor2(duration, color) {
console.log(duration, color)
if (color === 'red') {
red.classList.add('red');
yellow.classList.remove('yellow')
green.classList.remove('green')
} else if (color === 'yellow') {
yellow.classList.add('yellow');
red.classList.remove('red')
green.classList.remove('green')
} else {
green.classList.add('green');
red.classList.remove('red')
yellow.classList.remove('yellow')
}
await sleep(duration);
}
async function main2(){
while(true){
await changeColor2(3000,"green");
await changeColor2(1000, "yellow");
await changeColor2(2000, "red");
}
}
main2()
</script>
</body>
</html>