请用JavaScript写一个红绿灯,单击时变色
时间: 2023-06-05 08:06:54 浏览: 79
很高兴为您解答问题!以下是JavaScript实现红绿灯的代码:
HTML部分:
```html
<div id="traffic-light">
<div class="light red"></div>
<div class="light yellow"></div>
<div class="light green"></div>
</div>
<button onclick="changeColor()">点击切换</button>
```
CSS部分:
```css
#traffic-light {
display: flex;
justify-content: center;
align-items: center;
height: 150px;
}
.light {
width: 80px;
height: 80px;
border-radius: 50%;
margin: 0 20px;
box-shadow: 0 0 10px #333;
}
.red {
background-color: red;
}
.yellow {
background-color: yellow;
}
.green {
background-color: green;
}
```
JavaScript部分:
```javascript
let lightIndex = 0;
let lights = document.getElementsByClassName("light");
function changeColor() {
// 所有灯变灰
for (let i = 0; i < lights.length; i++) {
lights[i].style.backgroundColor = "gray";
}
// 当前灯变红、黄或绿
if (lightIndex === 0) {
lights[0].style.backgroundColor = "red";
} else if (lightIndex === 1) {
lights[1].style.backgroundColor = "yellow";
} else if (lightIndex === 2) {
lights[2].style.backgroundColor = "green";
}
// lightIndex 加 1,如果大于 2,则重置为 0
lightIndex = (lightIndex + 1) % 3;
}
```
以上代码实现了一个简单的红绿灯,点击按钮可以切换三种颜色状态。当然,红绿灯的实际应用要更加复杂,需要考虑时间、车辆、行人等因素,以上代码仅供参考。