一、实现效果
绿(10秒)→黄(5秒)→红(10秒)→绿(10秒)…依次循环。
二、代码分析
首先编写html代码,使用CSS确定需要改变的div。其次编写JavaScript代码,通过修改背景颜色的方式,设置信号灯样式。最后实现红绿灯读秒,利用setInterval()和setTimeout()函数完成信号灯读秒的动态改变效果。
三、代码实现
1.编写HTML代码
<body>
<div class="trfc_lts1">
<div id="redLight" class="light"></div> <!-- 红灯 -->
<div id="yellowLight" class="light"></div> <!-- 黄灯 -->
<div id="greenLight" class="light"></div> <!-- 绿灯 -->
</div>
<div id="countDown"></div> <!-- 倒计时 -->
<button onclick="startChange()">开始工作</button>
</body>
2.初始化
将三块颜色全部变白,可以不写。
function startChange() {
let redObj = document.getElementById("redLight");
let yellowObj = document.getElementById("yellowLight");
let greenObj = document.getElementById("greenLight");
redObj.style.backgroundColor = "white";
yellowObj.style.backgroundColor = "white";
greenObj.style.backgroundColor = "white";
toGreen();
}
toGreen():使信号灯由红变绿。
3.实现红绿灯变化
这里以变成绿色为例,变成其他颜色的函数是类似的。
function toGreen() { <!-- 变成绿色 -->
let redObj = document.getElementById("redLight");
let greenObj = document.getElementById("greenLight");
redObj.style.backgroundColor = "white";
greenObj.style.backgroundColor = "green";
document.getElementById('countDown').style.color='green';//数字颜色相应信号灯改变
let timer = 9;
countDown(timer);
setTimeout("toYellow()",(timer+1)*1000); <!-- 1000ms == 1s -->
}
timer:存储对应信号灯剩余亮灯时间。(注:这里的timer赋值为9(少了一秒),是由于单线程的缘故,颜色改变的同时倒计时并不会开始(会等一秒),因此在后面的countDown()函数和setTimeout里对timer加一,对齐时间。)
countDown():倒计时函数。
4.实现红绿灯倒计时
function countDown(timer){
document.getElementById('countDown').innerHTML = timer+1; //对应颜色显示初始数字
setInterval(() => {
if (timer >= 0) {
document.getElementById('countDown').innerHTML = timer--; //倒数
}
}, 1000);
}
利用setInterval()函数,在每隔1秒钟间歇调用一次匿名函数。
5.CSS相关
.trfc_lts1{
width: 220px;
height: 618px;
float: left;
border: 1px solid black;
}
.trfc_lts1 .light{
width: 200px;
height: 200px;
border-radius: 100%;
border:3px solid black;
}
.trfc_lts1 #redLight{
background-color: red;
margin-left: 7px;
}
.trfc_lts1 #yellowLight{
background-color: yellow;
margin-left: 7px;
}
.trfc_lts1 #greenLight{
background-color: green;
margin-left: 7px;
}
#countDown{
margin-left: 10px;
width: 202px;
height: 202px;
font-size: 155px;
float: left;
border: 2px solid black;
background-color: gray;
}
总结
感谢文章javascript并行执行详解给予的启发。
如果对你有所帮助,别忘了帮忙点个赞!!!