用JS编写,红绿灯倒计时:实现三色交通信号灯的亮灯的顺序一般为“绿->黄->红->绿”依次循环。亮灯时长需根据路口的实际情况等因素来考虑设置,如红灯亮为30秒,绿灯亮为35秒,黄灯亮为5秒。
CSS页面代码:<style>*{margin: 0;padding: 0;}.signal-light{width: 400px;margin: 100px auto 0;}.light{display: flex;margin: 0 auto;width: 140px;height: 500px;flex-di
·
CSS页面代码:
<style>
*{
margin: 0;
padding: 0;
}
.signal-light{
width: 400px;
margin: 100px auto 0;
}
.light{
display: flex;
margin: 0 auto;
width: 140px;
height: 500px;
flex-direction: column;
align-items: center;
border-radius: 70px;
background-color: #333;
}
.light div{
width: 100px;
height: 100px;
margin-top: 20px;
border-radius: 100px;
background-color: #eee;
}
.light div.countdown{
text-align: center;
font-size: 48px;
line-height: 100px;
}
#red.active{
background-color: red;
}
#yellow.active{
background-color: yellow;
}
#green.active{
background-color:green;
}
HTML页面代码:
<div class="signal-light">
<div class="light">
<div id="red"></div>
<div id="yellow"></div>
<div id="green"></div>
<div class="countdown" id="countdown"></div>
</div>
</div>
JS页面代码:
<script>
// 获取ID
function getELeById(id){
return document.getElementById(id);
}
// 信号灯构造函数
function SignalLight(ele,timeout,nextLight){
this.ele=ele;
this.timeout=timeout;
this.nextLight=nextLight;
}
SignalLight.prototype.clearColor=function(){
this.ele.className='';
}
// 修改信号灯的颜色
SignalLight.prototype.changeColor=function(){
this.ele.className='active';
}
SignalLight.prototype.changeNum=function(num){
getELeById('countdown').innerHTML=num<10?'0'+num:num;
}
var red=new SignalLight(getELeById('red'),30,'green');
var yellow=new SignalLight(getELeById('yellow'),5,'red');
var green=new SignalLight(getELeById('green'),35,'yellow');
var nowLight=green;
var timeout=nowLight.timeout;
nowLight.changeColor();
nowLight.changeNum(timeout);
setInterval(function(){
--timeout;
if(timeout<=0){
nowLight.clearColor();
nowLight=window[nowLight.nextLight];
timeout=nowLight.timeout;
nowLight.changeColor();
}
nowLight.changeNum(timeout);
},1000);
</script>
运行结果如图:
更多推荐
已为社区贡献1条内容
所有评论(0)