<style>
* {
margin: 0;
padding: 0;
}
ul,
li {
list-style: none;
}
#light {
width: 260px;
display: flex;
justify-content: space-evenly;
}
#light li {
height: 50px;
width: 50px;
border-radius: 50%;
opacity: .1;
}
#light #green {
background: green;
}
#light #yellow {
background: yellow;
}
#light #red {
background: red;
}
.green #green,
.yellow #yellow,
.red #red {
opacity: 1;
}
</style>
</head>
<body>
<!-- html -->
<ul id="light" class="">
<li id="green"></li>
<li id="yellow"></li>
<li id="red"></li>
</ul>
<!-- js -->
<script>
//绿灯 3s 黄灯1s 红灯3s
let oLight = document.getElementById("light");
//方法1******************
function start(){
oLight.className="green";
setTimeout(function(){
oLight.className="yellow";
setTimeout(()=>{
oLight.className="red";
setTimeout(()=>{
start();
},3000)
},1000)
},3000);
}
start();
//方法2*****************
function timeout(interval) {
return new Promise((resolve, reject)=>{
setTimeout(resolve, interval);
});
}
function start() {
oLight.className = "green";
timeout(3000).then(() => {
oLight.className = "yellow";
return timeout(1000);
}).then(() => {
oLight.className = "red";
return timeout(3000);
}).then(() => {
start();
})
}
start();
</script>
</body>
demo-红绿灯
最新推荐文章于 2022-08-10 16:06:57 发布