交通信号灯实现
Favori,
图:Mako Tsereteli
实现一
纯js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>红绿灯</title>
<style>
#traffic-light {
width: 100px;
height: 100px;
border-radius: 50%;
overflow: hidden;
border: 1px solid #f1f1f1;
}
</style>
</head>
<body>
<div id="traffic-light"></div>
<script src="index.js"></script>
</body>
</html>
const TRAFFIC_LIGHT_CONFIG = {
green: 3000,
yellow: 1000,
red: 2000,
};
function delay(duration) {
return new Promise((resolve, reject) => {
setTimeout(resolve, duration);
});
}
async function changeColor(color) {
document.getElementById("traffic-light").style.background = color;
await delay(TRAFFIC_LIGHT_CONFIG[color]);
}
// 通过配置文件来控制顺序
async function run() {
for (let key in TRAFFIC_LIGHT_CONFIG) {
await changeColor(key);
}
run();
}
run();
实现二
纯css
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>红绿灯</title>
<style>
#traffic-light {
width: 100px;
height: 100px;
border-radius: 50%;
background: red;
animation: hld 6s step-end infinite;
}
@keyframes hld {
0% { background: red; }
50% { background: yellow; }
66.67% { background: green; }
}
</style>
</head>
<body>
<div id="traffic-light"></div>
</body>
</html>