html 制作交通信号灯倒计时
时间: 2023-06-17 17:06:26 浏览: 118
要制作交通信号灯倒计时,需要使用 HTML、CSS 和 JavaScript 来实现。下面是一个简单的示例:
HTML 代码:
```html
<div class="traffic-light">
<div class="red"></div>
<div class="yellow"></div>
<div class="green"></div>
</div>
<div class="countdown">
<span id="countdown-text"></span>
</div>
```
CSS 代码:
```css
.traffic-light {
display: flex;
flex-direction: column;
}
.traffic-light > div {
width: 50px;
height: 50px;
border-radius: 50%;
margin-bottom: 10px;
}
.red {
background-color: red;
}
.yellow {
background-color: yellow;
}
.green {
background-color: green;
}
.countdown {
margin-top: 20px;
font-size: 24px;
font-weight: bold;
}
```
JavaScript 代码:
```javascript
// 设置倒计时时间(单位:秒)
var countdownTime = 30;
// 获取元素
var countdownText = document.getElementById("countdown-text");
var redLight = document.querySelector(".red");
var yellowLight = document.querySelector(".yellow");
var greenLight = document.querySelector(".green");
// 定义倒计时函数
function countdown() {
countdownTime--;
countdownText.textContent = countdownTime;
if (countdownTime == 20) {
greenLight.style.backgroundColor = "gray";
yellowLight.style.backgroundColor = "yellow";
} else if (countdownTime == 10) {
yellowLight.style.backgroundColor = "gray";
redLight.style.backgroundColor = "red";
} else if (countdownTime == 0) {
redLight.style.backgroundColor = "gray";
countdownText.textContent = "停止";
clearInterval(intervalId);
}
}
// 启动倒计时
var intervalId = setInterval(countdown, 1000);
```
运行上述代码,就可以看到一个交通信号灯和倒计时器的效果。在倒计时器倒计时过程中,交通信号灯的颜色也会随之变换。
阅读全文