Promise加定时器setInterval实现红绿灯倒计时

红绿灯

<style type="text/css">
			ul{
   
				width: 500px;
				display: flex;
				justify-content: space-around;
				background-color: #333;
				border-radius: 70px;
			}
			li{
   
				list-style: none;
				width: 50px;
				height: 50px;
				border-radius: 50%;
				opacity: .1;
			}
			ul li:last-child{
   
				opacity: 1;
				background-color: #eee;
				line-height: 50px;
				text-align: center;
				
			}
			#green{
   
				background: green;
			}
			#y
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的红绿灯倒计时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秒,然后再次循环。你可以根据需求修改倒计时的时间。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值