红绿灯
<style type="text/css">
ul{
width: 500px;
display: flex;
justify-content: space-around;
background-color: #333;
border-radius: 70px;
}
li{
list-style: none;
width: 50px;
height: 50px;
border-radius: 50%;
opacity: .1;
}
ul li:last-child{
opacity: 1;
background-color: #eee;
line-height: 50px;
text-align: center;
}
#green{
background: green;
}
#yellow{
background: yellow;
}
#red{
background: red;
}
.green #green,.yellow #yellow,.red #red{
opacity: 1;
}
</style>`
``
```html
`<ul id="light" class="">
<li id="green"></li><li id="yellow"></li><li id="red"></li><li id="jishi">10</li>
</ul>
这里要注意count=0时要选择变成什么样的红绿灯,相当于这里占了一秒,所以数字也要改变,下次启动定时器时要先count- -,这样才能符合要求的倒计时秒数,最后注意记得清除定时器。
<script type="text/javascript">
//绿灯 3 黄灯1 红灯3
var oLight = document.getElementById("light");
var flag;
oLight.className = "green";
flag=2;
function getELeById(id){
return document.getElementById(id);
}
function timeout(interval){
let count=interval/1000;
return new Promise((resolve,reject)=>{
var timer=setInterval(function(){
count--;
console.log(count);
if(count==0){
clearInterval(timer);
resolve();
if(flag==1){
oLight.className = "green";
getELeById('jishi').innerHTML=10;
flag=2;}
else if(flag==2){
oLight.className = "yellow";
flag=3;
getELeById('jishi').innerHTML='05';
} else{
oLight.className = "red";
flag=1;
getELeById('jishi').innerHTML='10';
}
}
else {
getELeById('jishi').innerHTML=count<10?'0'+count:count;
}
},1000);
})
}
function start(){
timeout(10000).then(()=>{
return timeout(5000);
}).then(()=>{
return timeout(10000);
}).then(()=>{
start();
})
}
start();
</script>