用原生js写绿灯显示3秒黄灯1秒红灯2秒 并且循环显示

前几天面试要求用原生js写这个,当时写了,没写完,说了自己的思路,面试官说你已经写了很长时间了,算是没戏了,这么简单的一个题目,现在用能想到的几种方法(css3,js)写下

第一种:函数式(js)

html结构如下

<div id="light" class="green"> </div>

<style type="text/css">
  #light{width:200px; height:200px; animation: hld 6s ease  infinite}
  .green{background: green;}
  .yellow{background: yellow;}
  .red{background: red;}

</style>

<script type="text/javascript">
  function toGreen(){
    document.getElementById("light").style.background = 'green';
    setTimeout(toYellow,3000)
  }
  function toYellow(){
    document.getElementById("light").style.background = 'yellow';
    setTimeout(toRed,1000)
  }
  function toRed(){
    document.getElementById("light").style.background = 'red';
    setTimeout(toGreen,2000)
  }
  toGreen();
</script>

效果如下:

第二种

 

 function hld(light) {      
        this.light = document.getElementById(light);
      }

          
      hld.prototype.turn = function() {      
        var light = this.light;

              
        (function turnColoe() {        
          var that = this;        
          setTimeout(function() {          
            light.className = 'yellow';           
            setTimeout(function() {            
              light.className = 'red';              
              setTimeout(function() {                 
                light.className = 'green';                 
                setTimeout(turnColoe(), 0);              
              }, 2000);          
            }, 1000)        
          }, 3000)      
        })()    
      }

          
      function ele(n) {      
        var test = new hld(n);      
        return test;    
      }

          
      ele('light').turn();

 

 第三种

纯css3 动画animation 写

<style type="text/css">
      #light {
        width: 200px;
        height: 200px;
        animation: hld 6s ease infinite
      }
      
      @keyFrames hld{
    0% {
      background: green
    }
    50%
    {
      background: yellow
    }
    67% {
      background: red
    }
  }
    </style> 

效果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值