js红绿灯倒计时
时间: 2023-07-23 14:15:34 浏览: 69
以下是一个简单的红绿灯倒计时的JavaScript代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<title>红绿灯倒计时</title>
</head>
<body>
<div id="traffic-light">
<div class="red"></div>
<div class="yellow"></div>
<div class="green"></div>
</div>
<p id="timer"></p>
<script>
var redTime = 10; // 红灯倒计时时间(秒)
var yellowTime = 3; // 黄灯倒计时时间(秒)
var greenTime = 15; // 绿灯倒计时时间(秒)
var redLight = document.querySelector('.red');
var yellowLight = document.querySelector('.yellow');
var greenLight = document.querySelector('.green');
var timer = document.querySelector('#timer');
function startRedLight() {
redLight.classList.add('active');
timer.textContent = redTime + ' 秒';
var redTimer = setInterval(function(){
redTime--;
timer.textContent = redTime + ' 秒';
if (redTime == 0) {
clearInterval(redTimer);
redLight.classList.remove('active');
startYellowLight();
}
}, 1000);
}
function startYellowLight() {
yellowLight.classList.add('active');
timer.textContent = yellowTime + ' 秒';
var yellowTimer = setInterval(function(){
yellowTime--;
timer.textContent = yellowTime + ' 秒';
if (yellowTime == 0) {
clearInterval(yellowTimer);
yellowLight.classList.remove('active');
startGreenLight();
}
}, 1000);
}
function startGreenLight() {
greenLight.classList.add('active');
timer.textContent = greenTime + ' 秒';
var greenTimer = setInterval(function(){
greenTime--;
timer.textContent = greenTime + ' 秒';
if (greenTime == 0) {
clearInterval(greenTimer);
greenLight.classList.remove('active');
startRedLight();
}
}, 1000);
}
startRedLight(); // 开始红灯倒计时
</script>
<style>
#traffic-light {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 50px;
}
#traffic-light > div {
width: 100px;
height: 100px;
border-radius: 50%;
margin-bottom: 20px;
}
.red {
background-color: red;
}
.yellow {
background-color: yellow;
}
.green {
background-color: green;
}
.active {
box-shadow: 0 0 5px 5px rgba(255, 255, 255, 0.5);
}
#timer {
font-size: 30px;
text-align: center;
margin-top: 20px;
}
</style>
</body>
</html>
```
该代码会在页面上显示一个红绿灯,同时在下方显示倒计时。红灯持续10秒,黄灯持续3秒,绿灯持续15秒,然后再次循环。你可以根据需求修改倒计时的时间。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)