用javascript实现红绿灯效果功能描述要求如下 红灯绿 灯亮灯市长均为30秒黄灯亮灯时长为3秒 3实现效果要求有红绿黄三色灯有倒计时屏幕
显示,能够自动循环播放红绿灯效果。
实现思路:
- 通过DOM操作获取红绿黄三个灯的元素,并定义每个灯亮起和熄灭的样式。
- 定义一个计时器函数,利用setTimeout()方法来实现倒计时功能。当倒计时结束后,重新调用计时器函数,实现循环播放。
- 在计时器函数中,根据倒计时时间的不同,切换不同的灯亮起和熄灭的状态。
- 在页面中添加一个倒计时屏幕元素,并在计时器函数中更新倒计时时间的显示。
代码如下:
HTML代码:
<div id="trafficLight">
<div id="redLight"></div>
<div id="yellowLight"></div>
<div id="greenLight"></div>
</div>
<div id="countdown"></div>
CSS代码:
#trafficLight {
width: 100px;
height: 300px;
background-color: #000;
border-radius: 10px;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
padding: 10px;
}
#redLight, #yellowLight, #greenLight {
width: 80px;
height: 80px;
border-radius: 50%;
margin: 10px;
}
#redLight {
background-color: #f00;
}
#yellowLight {
background-color: #ff0;
}
#greenLight {
background-color: #0f0;
}
#countdown {
font-size: 50px;
font-weight: bold;
color: #fff;
margin-top: 20px;
}
JavaScript代码:
var redLight = document.getElementById("redLight");
var yellowLight = document.getElementById("yellowLight");
var greenLight = document.getElementById("greenLight");
var countdown = document.getElementById("countdown");
function startTimer() {
var redTime = 30;
var yellowTime = 3;
var greenTime = 30;
function updateRedLight() {
redLight.style.backgroundColor = "#f00";
yellowLight.style.backgroundColor = "#000";
greenLight.style.backgroundColor = "#000";
countdown.innerHTML = redTime;
redTime--;
if (redTime < 0) {
clearInterval(timer);
setTimeout(startTimer, 1000);
}
}
function updateYellowLight() {
redLight.style.backgroundColor = "#000";
yellowLight.style.backgroundColor = "#ff0";
greenLight.style.backgroundColor = "#000";
countdown.innerHTML = yellowTime;
yellowTime--;
if (yellowTime < 0) {
clearInterval(timer);
setTimeout(startTimer, 1000);
}
}
function updateGreenLight() {
redLight.style.backgroundColor = "#000";
yellowLight.style.backgroundColor = "#000";
greenLight.style.backgroundColor = "#0f0";
countdown.innerHTML = greenTime;
greenTime--;
if (greenTime < 0) {
clearInterval(timer);
setTimeout(startTimer, 1000);
}
}
updateRedLight();
var timer = setInterval(function() {
if (redTime >= 0) {
updateRedLight();
} else if (yellowTime >= 0) {
updateYellowLight();
} else {
updateGreenLight();
}
}, 1000);
}
startTimer();
``
原文地址: https://www.cveoy.top/t/topic/gSgx 著作权归作者所有。请勿转载和采集!