<div class="box">
<div class="green"></div>
<div class="red"></div>
<div class="yeoolw"></div>
</div>
<div class="gz"></div>
*{
margin: 0;
padding: 0;
}
.box{
width: 100px;
height: 50px;
display: flex;
justify-content: center;
align-items: center;
background-color: darkgray;
margin-top: 200px;
margin-left: 100px;
}
.green{
width: 30px;
height: 30px;
margin: 5px;
background: darkgreen;
border-radius: 50%;
opacity: 0.3;
}
.red{
width: 30px;
height: 30px;
margin: 5px;
border-radius: 50%;
background: red;
opacity: 0.3;
}
.yeoolw{
width: 30px;
height: 30px;
margin: 5px;
border-radius: 50%;
background: yellow;
opacity: 0.3;
}
.gz{
width: 20px;
height: 150px;
position: relative;
background: darkgray;
top:1px;
left: 100px;
}
.light{
opacity: 1;
}
function x(){
r_1()//红灯亮
setTimeout(y_1, 1000);//黄灯一秒后亮
setTimeout(r_1, 1000);//黄灯亮的同时关闭红灯
setTimeout(g_1, 2000);//绿灯两秒后亮
setTimeout(y_1, 2000);//绿灯亮,黄灯熄
setTimeout(g_1, 3000);//三秒后,红灯熄
}
function r_1(){
var r=document.querySelector('.red');
r.classList.toggle('light');
}
function g_1(){
var g=document.querySelector('.green');
g.classList.toggle('light');
}
function y_1(){
var y=document.querySelector('.yeoolw');
y.classList.toggle('light');
}
x();
window.onload = function () {
t1 = setInterval(x, 3000)//每隔三秒重复执行函数
};
比较简单吧,就是通过 setTimeout,然后通过toggle切换一下样式,自我感觉重复率太高,值得优化一下代码