用javascript实现红绿灯效果功能描述要求如下 黄灯亮灯时长为3秒实现效果要求有红绿黄三色灯有倒计时屏幕 红灯绿 灯 亮灯市长均为30秒黄灯亮灯时长为3秒
HTML部分:
<div id="traffic-light">
<div class="light red"></div>
<div class="light yellow"></div>
<div class="light green"></div>
</div>
<div id="countdown"></div>
CSS部分:
#traffic-light {
width: 80px;
height: 200px;
position: relative;
}
.light {
width: 60px;
height: 60px;
border-radius: 50%;
position: absolute;
left: 50%;
transform: translateX(-50%);
}
.red {
background-color: red;
top: 20px;
}
.yellow {
background-color: yellow;
top: 90px;
}
.green {
background-color: green;
top: 160px;
}
#countdown {
font-size: 30px;
text-align: center;
margin-top: 20px;
}
Javascript部分:
var redTime = 30; // 红灯时间
var yellowTime = 3; // 黄灯时间
var greenTime = 30; // 绿灯时间
var countdownTime = redTime + yellowTime + greenTime; // 倒计时总时间
var timer;
function startCountdown() {
var countdownElem = document.getElementById("countdown");
var redElem = document.querySelector(".red");
var yellowElem = document.querySelector(".yellow");
var greenElem = document.querySelector(".green");
timer = setInterval(function() {
countdownTime--;
if (countdownTime == 0) {
clearInterval(timer);
startCountdown();
} else if (countdownTime <= redTime) {
redElem.style.opacity = 1;
yellowElem.style.opacity = 0;
greenElem.style.opacity = 0;
countdownElem.innerHTML = countdownTime + "秒 红灯";
} else if (countdownTime > redTime && countdownTime <= redTime + yellowTime) {
redElem.style.opacity = 0;
yellowElem.style.opacity = 1;
greenElem.style.opacity = 0;
countdownElem.innerHTML = countdownTime + "秒 黄灯";
} else {
redElem.style.opacity = 0;
yellowElem.style.opacity = 0;
greenElem.style.opacity = 1;
countdownElem.innerHTML = countdownTime + "秒 绿灯";
}
}, 1000);
}
startCountdown();
效果如下:
![红绿灯效果](https://i.loli.net/2021/08/19/Yh1QmJvzIjB9uiG.png
原文地址: https://www.cveoy.top/t/topic/gSim 著作权归作者所有。请勿转载和采集!