实现交通灯效果

主体结构

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

posted on 2017-01-12 19:58  路人华  阅读(452)  评论(0编辑  收藏  举报

导航