重学前端红绿灯实现

4次阅读

共计 757 个字符,预计需要花费 2 分钟才能阅读完成。

实现一个红绿灯,把一个圆形 div 依照绿色 3 秒,黄色 1 秒,红色 2 秒循环扭转背景色。

<!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 class="traffic-light"></div>
    <script>
        function keepColor(duration) {return new Promise((resolve, reject) => {setTimeout(resolve, duration);
            });
        }
        async function changeColor (color, duration) {document.getElementsByClassName('traffic-light')[0].style.background = color;
            await keepColor(duration);
        }
        async function run() {while (1) {await changeColor('green', 3000); // await 要嵌套,最里层有外层兴许有
                await changeColor('yellow', 1000);
                await changeColor('red', 2000);
            }
        }
        run();
    </script>
</body>
</html>
正文完
 0