您的位置:首页 > Web前端 > JavaScript

JavaScript_实现红绿灯倒计时效果

2020-02-03 02:01 1346 查看

红绿灯倒计时

1.效果
绿灯亮(35秒)-黄灯亮(5秒)-红灯亮(30秒)-绿灯亮(35秒)无限循环,实现红绿灯倒计时效果。
2.代码解析
(1)编写HTML代码

<div class="box">
<div id="red"></div>
<div id="yellow"></div>
<div id="green"></div>
<div class="count" id="count"></div>
</div>

(2)编写盒子模型样式

<style>
.box{width:300px;height:60px;padding:22px 30px;border:300px solid #ccc;border-radius:200px;margin:0 auto;}
.box .count{width:60px;color:#666;font-size:280%;line-height:50px;padding-left:10px;margin-left:5px;border:1px solid #fff}
.box div{margin-left:5px;float:left;width:50px;height:50px;border-radius:10px;border:5px solid #666;}
.gray{background-color:#eee;}
.red{background-color:red;}
.yellow{background-color:yellow;}
.green{background-color:#26ff00;}
</style>

(3)创建红绿灯对象

var lamp = {
red: {
obj: document.getElementById('red'),
timeout: 1,
style: ['red', 'gray', 'gray'],
next: 'green'
},
yellow: {
obj: document.getElementById('yellow'),
timeout: 1,
style: ['gray', 'yellow', 'gray'],
next: 'red'
},
green: {
obj: document.getElementById('green'),
timeout: 1,
style: ['gray', 'gray', 'green'],
next: 'yellow'
},
changeStyle(style) {
this.red.obj.className = style[0];
this.yellow.obj.className = style[1];
this.green.obj.className = style[2];
}
};

(4)创建倒计时对象

var count = {
obj: document.getElementById('count'),
change: function(num) {
this.obj.innerHTML = (num < 10) ? ('0' + num) : num;
}
};

(5)初始化界面

var now = lamp.green;
var timeout = now.timeout;
lamp.changeStyle(now.style);
count.change(timeout);

(6)实现红绿灯倒计时

setInterval(function() {
if (--timeout <= 0) {
now = lamp[now.next];
timeout = now.timeout;
lamp.changeStyle(now.style);
}
count.change(timeout);
}, 1000);
  • 点赞
  • 收藏
  • 分享
  • 文章举报
涡轮发动机i 发布了9 篇原创文章 · 获赞 0 · 访问量 454 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: