实现一
纯js
1<!DOCTYPE html>2<html lang="en">3 <head>4 <meta charset="UTF-8" />5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />6 <title>红绿灯</title>7 <style>8 #traffic-light {9 width: 100px;10 height: 100px;11 border-radius: 50%;12 overflow: hidden;13 border: 1px solid #f1f1f1;14 }15 </style>16 </head>17 <body>18 <div id="traffic-light"></div>19 <script src="index.js"></script>20 </body>21</html>
1const TRAFFIC_LIGHT_CONFIG = {2 green: 3000,3 yellow: 1000,4 red: 2000,5};67function delay(duration) {8 return new Promise((resolve, reject) => {9 setTimeout(resolve, duration);10 });11}1213async function changeColor(color) {14 document.getElementById("traffic-light").style.background = color;15 await delay(TRAFFIC_LIGHT_CONFIG[color]);16}1718// 通过配置文件来控制顺序19async function run() {20 for (let key in TRAFFIC_LIGHT_CONFIG) {21 await changeColor(key);22 }23 run();24}25run();
实现二
纯css
1<!DOCTYPE html>2<html lang="en">3<head>4 <meta charset="UTF-8">5 <meta name="viewport" content="width=device-width, initial-scale=1.0">6 <title>红绿灯</title>7 <style>8 #traffic-light {9 width: 100px;10 height: 100px;11 border-radius: 50%;12 background: red;13 animation: hld 6s step-end infinite;14 }15 @keyframes hld {16 0% { background: red; }17 50% { background: yellow; }18 66.67% { background: green; }19 }20 </style>21</head>22<body>23 <div id="traffic-light"></div>24</body>25</html>