如何用JavaScript编程来模拟交通信号灯(红绿灯)效果,并同时显示每个阶段的倒计时计数?
时间: 2024-10-25 08:17:16 浏览: 16
在JavaScript中,我们可以使用定时器函数setTimeout或者setInterval配合HTML和CSS来实现一个简单的交通信号灯效果。以下是一个基本的步骤:
1. **HTML结构**:
```html
<div class="traffic-light">
<div id="signal" class="phase"></div>
</div>
<ul class="timer"> <!-- 显示倒计时计数 -->
<li>Red: <span id="red-time">0</span></li>
<li>Yellow: <span id="yellow-time">0</span></li>
<li>Green: <span id="green-time">0</span></li>
</ul>
```
2. **CSS样式**:
```css
.phase {
width: 50px;
height: 50px;
background-color: red;
position: relative;
transition: background-color 1s; /* 淡入淡出效果 */
}
.signal {
display: none;
}
```
3. **JavaScript代码**:
```javascript
let signal = document.getElementById('signal');
let phases = ['red', 'yellow', 'green'];
let phaseIndex = 0;
let durations = { red: 3000, yellow: 1000, green: 3000 };
function changePhase() {
signal.classList.remove('active');
signal.className = phases[phaseIndex];
let timeElement = document.querySelector(`#${phases[phaseIndex]}-time`);
if (phaseIndex === 0) { // 如果是红色
timeElement.textContent = durations.red;
setTimeout(startCountdown, durations.red);
} else {
timeElement.textContent = '';
}
}
function startCountdown(time) {
let countdown = time;
const updateTimer = () => {
timeElement.textContent = `${countdown}ms`;
countdown -= 100; // 每隔100毫秒递减
if (countdown <= 0) {
endPhase();
} else {
setTimeout(updateTimer, 100);
}
};
updateTimer();
}
function endPhase() {
signal.classList.add('active');
signal.className = 'phase';
setTimeout(() => {
if (++phaseIndex >= phases.length) {
phaseIndex = 0; // 循环回到第一个阶段
}
changePhase();
}, durations[phases[phaseIndex]]);
}
// 初始化并开始红灯阶段
changePhase();
```
这个示例会在页面加载完成后开始一个循环,每3秒切换到下一个阶段(红灯、黄灯和绿灯),并在每个阶段结束时显示剩余时间。
阅读全文