实现交通灯效果

主体结构

1 <ul id="traffic">
2     <li><span></span></li>
3     <li><span></span></li>
4     <li><span></span></li>
5 </ul>

 

样式

 1      #traffic>li{
 2             display:block;
 3         }
 4         #traffic span{
 5             display:inline-block;
 6             width:50px;
 7             height:50px;
 8             background-color:gray;
 9             margin:5px;
10             border-radius:50%;
11             float:left;
12         }
13         #traffic.stop li:nth-child(1) span{
14             background-color:yellow;
15         }
16         #traffic.wait li:nth-child(2) span{
17             background-color:red;
18         }
19         #traffic.pass li:nth-child(3) span{
20             background-color:green;
21         }

 

 

js代码1--利用定时器改变类名

 1 const traffic = document.getElementById("traffic");
 2 (function reset(){
 3     traffic.className = "wait";
 4 
 5     setTimeout(function(){
 6         traffic.className = "stop";
 7         setTimeout(function(){
 8             traffic.className = "pass";
 9             setTimeout(reset,2000);
10         },2000);
11     },2000);
12 })();

 

 js代码2

1 const traffic = document.getElementById("traffic");
2 var stateList = ["wait", "stop", "pass"];
3 var currentStateIndex = 0;
4 setInterval(function(){
5     var state = stateList[currentStateIndex];
6     traffic.className = state;
7     currentStateIndex = (currentStateIndex + 1) % stateList.length;
8 },2000);

 

 

Save

Save

转载于:https://www.cnblogs.com/luren-hua/p/6279607.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值