分享一个好玩小案例(红绿灯)

 

<!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>
  <style type="text/css">
    div {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      border: 1px solid black;
      text-align: center;
      line-height: 50px;
      font-size: 30px;
      font-weight: bold;
      color: white;
    }

    #redLight {
      background-color: white;
    }

    #greenLight {
      background-color: white;
    }

    #yellowLight {
      background-color: white;
    }
  </style>
</head>

<body>
  <div id="redLight"></div><br>
  <div id="greenLight"></div><br>
  <div id="orangeLight"></div><br>
</body>

</html>
<script>
 function int(num,id,color){
    document.getElementById(id).style.backgroundColor=color;
    document.getElementById(id).innerHTML=num;
    return new Promise(function(resolve,reject){
      let time=setInterval(function(){
        num--;
        if(num<=0){
          num=0;
          clearInterval(time);
          time=undefined;
          document.getElementById(id).style.backgroundColor="white";
          resolve();
        }
        document.getElementById(id).innerHTML=num;
      },1000)
    })
    }
  function ints(){
          int(3,"redLight","red")
          .then(function(){
            return  int(3,"greenLight","green");
          })
          .then(function(){
            return int(3,"orangeLight","orange");
          })
          .then(ints);
        }
        ints();
</script>
// 红灯闪烁的代码

    function redShan() {

        let num = 3;
        document.getElementById("redLight").style.backgroundColor = "red";
        document.getElementById("redLight").innerHTML = num;

        return new Promise(function (resolve, reject) {

            let myTimer = setInterval(function () {

                num--;

                if (num <= 0) {//良性冗余
                    num = 0;
                    clearInterval(myTimer);
                    myTimer = undefined;
                    document.getElementById("redLight").style.backgroundColor = "white";
                    resolve();
                }

                document.getElementById("redLight").innerHTML = num;

            }, 1000)
        })
    }
//黄灯闪烁代码
//红灯闪烁代码
//...只是改变了获取的dom,以及一些style样式,造成代码冗余,所以上面的代码是对其的封装

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值