js红路灯倒计时变色
时间: 2024-06-22 10:01:25 浏览: 112
倒计时 vb 原创 颜色变化
JavaScript 可以用来创建一个红绿灯的倒计时变色效果。这通常涉及到使用定时器(如 `setInterval`)来控制灯的状态变化,结合 CSS 进行颜色变换。以下是一个简单的示例:
1. HTML 结构:
```html
<div id="traffic-light">
<div class="light red"></div>
<div class="light yellow"></div>
<div class="light green"></div>
</div>
```
2. CSS 用于颜色和样式:
```css
.red {
background-color: red;
}
.yellow {
background-color: yellow;
}
.green {
background-color: green;
}
.light {
width: 30px;
height: 30px;
display: inline-block;
transition: background-color 1s ease;
}
```
3. JavaScript 代码 (使用 ES6 语法):
```javascript
const trafficLight = document.getElementById('traffic-light');
const lightElements = trafficLight.getElementsByClassName('light');
let status = 0; // 0 - Red, 1 - Yellow, 2 - Green
function changeLightColor() {
lightElements.forEach((light) => {
if (status === 0) {
light.classList.add('red');
} else if (status === 1) {
light.classList.remove('red');
light.classList.add('yellow');
} else { // status === 2
light.classList.remove('yellow');
light.classList.add('green');
}
// Switch the status after a delay
setTimeout(() => {
status = (status + 1) % 3; // Loop back to 0 after green
}, 3000); // Change color every 3 seconds
});
}
// Start the countdown
changeLightColor();
```
阅读全文