非常抱歉,我遗漏了倒计时的数字显示。以下是修正后的代码,其中增加了倒计时的功能:HTML部分: <div class="traffic-light">
<div id="left-light" class="light red"></div>
<div id="straight-light" class="light green"></div>
<div id="right-light" class="light green"></div>
</div>
<div id="countdownBox">倒计时:<span id="countdownSeconds">10</span> 秒</div>
CSS部分:.traffic-light {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
}
.light {
width: 100px;
height: 100px;
border-radius: 50%;
margin: 10px;
}
.red {
background-color: red;
}
.green {
background-color: green;
}
.blink {
animation: blink 0.5s infinite alternate;
}
@keyframes blink {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
JavaScript部分:window.onload = function() {
var leftLight = document.getElementById("left-light");
var straightLight = document.getElementById("straight-light");
var rightLight = document.getElementById("right-light");
var countdownSecondsBox = document.getElementById("countdownSeconds");
var countdownSeconds = 10;
function countdown() {
if (countdownSeconds > 0) {
countdownSeconds--;
countdownSecondsBox.innerHTML = countdownSeconds;
}
}
function switchLights() {
// 左转红,直行绿
leftLight.classList.remove("green");
leftLight.classList.add("red");
straightLight.classList.remove("red");
straightLight.classList.add("green");
countdownSeconds = 10;
countdownSecondsBox.innerHTML = countdownSeconds;
// 直行黄闪
setTimeout(function() {
straightLight.classList.add("blink");
}, 5000);
// 左转绿
setTimeout(function() {
straightLight.classList.remove("green");
straightLight.classList.remove("blink");
leftLight.classList.remove("red");
leftLight.classList.add("green");
}, 7000);
// 直行红,左转红
setTimeout(function() {
leftLight.classList.remove("green");
leftLight.classList.add("red");
straightLight.classList.add("red");
}, 10000);
// 直行绿
setTimeout(function() {
straightLight.classList.remove("red");
straightLight.classList.add("green");
}, 12000);
// 直行红,左转绿
setTimeout(function() {
straightLight.classList.remove("green");
leftLight.classList.remove("red");
leftLight.classList.add("green");
}, 15000);
// 循环执行
setTimeout(switchLights, 17000);
}
switchLights();
setInterval(countdown, 1000);
};
现在倒计时的数字应该会出现在页面上方的倒计时框内,并且在倒计时结束后重新开始计时。希望这次的答案符合你的要求!
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |