原生js实现红绿灯展示

<!--
 * @Author: suoheng
 * @LastEditors: suoheng
 * @Date: 2021-09-24 14:57:44
 * @LastEditTime: 2021-09-24 15:14:56
 * @Email: secret
 * @FilePath: \js练习\红绿灯.html
 * @Description: 
 * @fileheader.Author: suoheng
 * @fileheader.LastModifiedBy: suoheng
-->
<!DOCTYPE html>
<html lang="en">

<head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
</head>

<body>
      <ul id="traffic" class="">
            <li id="green"></li>
            <li id="yellow"></li>
            <li id="red"></li>
      </ul>
</body>
<script>
      function timeout(timer) {
            return function () {
                  return new Promise(function (resolve, reject) {
                        setTimeout(resolve, timer)
                  })
            }
      }
      var green = timeout(3000);
      var yellow = timeout(4000);
      var red = timeout(5000);
      var traffic = document.getElementById("traffic");
      (function restart() {
            'use strict' //严格模式
            console.log("绿灯" + new Date().getSeconds()) //绿灯执行三秒 
            traffic.className = 'green';
            console.log(green())
            green()
                  .then(function () {
                        console.log("黄灯" + new Date().getSeconds()) //黄灯执行四秒
                        traffic.className = 'yellow';//黄灯的时候添加class类名,用于更换透明度,实现变色
                        return yellow();
                  })
                  .then(function () {
                        console.log("红灯" + new Date().getSeconds()) //红灯执行五秒
                        traffic.className = 'red';
                        return red();
                  }).then(function () {
                        restart() //循环调用
                  })
      })();
      (function test(){
            console.log("测试立即调用函数")
      })()
</script>
<style>
      ul {
            position: absolute;
            width: 200px;
            height: 200px;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
      }

      /*画3个圆代表红绿灯*/
      ul>li {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            opacity: 0.2;
            display: inline-block;
      }

      /*执行时改变透明度*/
      ul.red>#red,
      ul.green>#green,
      ul.yellow>#yellow {
            opacity: 1.0;
      }

      /*红绿灯的三个颜色*/
      #red {
            background: red;
      }

      #yellow {
            background: yellow;
      }

      #green {
            background: green;
      }
</style>

</html>

猜你喜欢

转载自blog.csdn.net/qq_41579104/article/details/120455790