描述:
简单的信号灯,信号灯分为绿——黄——红,具体流程是先绿灯,再黄灯,后红灯,红灯过后直接绿灯,循环往复,可以设置相应的响应时间。
通过 setTimeout来实现:
效果:
代码:
html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>信号灯</title>
<style>
* {
margin: 0;
padding: 0;
}
#shell {
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
width: 200px;
height: 440px;
background-color: rgb(85, 83, 81);
border-radius: 60px;
margin: 100px auto;
}
.circle {
background-color: black;
border-radius: 50%;
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div id="shell">
<div class="circle" id="c1"></div>
<div class="circle" id="c2"></div>
<div class="circle" id="c3"></div>
</div>
</body>
<script src="./deng.js"></script>
</html>
js:
//设置信号灯
function setColor(Deng) {
if (Deng == 'c1')//绿灯设置
document.getElementById(Deng).style.backgroundColor = 'green';
else if (Deng == 'c2')//黄灯设置
document.getElementById(Deng).style.backgroundColor = 'yellow';
else if (Deng == 'c3')//红灯设置
document.getElementById(Deng).style.backgroundColor = 'red';
}
//切换过程中的关闭信号灯
function setColorOff(Deng){
document.getElementById(Deng).style.backgroundColor = 'black';
}
//时间设置 3s 1s 3s
function startWork() {
setColor('c1')
setTimeout(() => {
setColorOff('c1')
setColor('c2')
setTimeout(() => {
setColorOff('c2')
setColor('c3')
setTimeout(() => {
setColorOff('c3')
startWork()
}, 3000)
}, 1000)
}, 3000)
}
startWork();