js编码实现,红灯三秒亮一次,绿灯一秒亮一次,黄灯两秒亮一次,三个灯不断交替重复亮灯
时间: 2023-10-05 20:09:53 浏览: 74
可以使用 setInterval() 函数来实现灯光的循环显示,同时可以使用 CSS 来设置灯光的颜色和亮灭状态。以下是实现代码:
HTML:
```html
<div class="traffic-light">
<div class="red-light"></div>
<div class="yellow-light"></div>
<div class="green-light"></div>
</div>
```
CSS:
```css
.traffic-light {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 200px;
}
.light {
width: 50px;
height: 50px;
border-radius: 50%;
box-shadow: 0px 0px 20px rgba(255, 255, 255, 0.5);
}
.red-light {
background-color: #f00;
}
.yellow-light {
background-color: #ff0;
}
.green-light {
background-color: #0f0;
}
```
JavaScript:
```js
const redLight = document.querySelector('.red-light');
const yellowLight = document.querySelector('.yellow-light');
const greenLight = document.querySelector('.green-light');
let currentLight = 'red';
setInterval(() => {
if (currentLight === 'red') {
redLight.classList.add('light');
greenLight.classList.remove('light');
setTimeout(() => {
currentLight = 'green';
}, 3000);
} else if (currentLight === 'green') {
yellowLight.classList.add('light');
redLight.classList.remove('light');
setTimeout(() => {
currentLight = 'yellow';
}, 1000);
} else {
yellowLight.classList.remove('light');
greenLight.classList.add('light');
setTimeout(() => {
currentLight = 'red';
}, 2000);
}
}, 4000);
```
该代码会在 HTML 中创建一个交通灯的容器,同时使用 CSS 设置了灯光的样式。在 JavaScript 中,我们使用 setInterval() 函数来循环执行灯光的变化。变量 currentLight 记录了当前显示的灯光,初始值为红灯。
在每个灯光的显示时间内,我们使用 setTimeout() 函数来设置下一个要显示的灯光,并在函数内修改 currentLight 变量的值。最后,我们将循环的时间设置为灯光的总显示时间(4秒)。