<!--
* @Author: suoheng
* @LastEditors: suoheng
* @Date: 2021-09-24 14:57:44
* @LastEditTime: 2021-09-24 15:14:56
* @Email: secret
* @FilePath: \js练习\红绿灯.html
* @Description:
* @fileheader.Author: suoheng
* @fileheader.LastModifiedBy: suoheng
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul id="traffic" class="">
<li id="green"></li>
<li id="yellow"></li>
<li id="red"></li>
</ul>
</body>
<script>
function timeout(timer) {
return function () {
return new Promise(function (resolve, reject) {
setTimeout(resolve, timer)
})
}
}
var green = timeout(3000);
var yellow = timeout(4000);
var red = timeout(5000);
var traffic = document.getElementById("traffic");
(function restart() {
'use strict' //严格模式
console.log("绿灯" + new Date().getSeconds()) //绿灯执行三秒
traffic.className = 'green';
console.log(green())
green()
.then(function () {
console.log("黄灯" + new Date().getSeconds()) //黄灯执行四秒
traffic.className = 'yellow';//黄灯的时候添加class类名,用于更换透明度,实现变色
return yellow();
})
.then(function () {
console.log("红灯" + new Date().getSeconds()) //红灯执行五秒
traffic.className = 'red';
return red();
}).then(function () {
restart() //循环调用
})
})();
(function test(){
console.log("测试立即调用函数")
})()
</script>
<style>
ul {
position: absolute;
width: 200px;
height: 200px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
/*画3个圆代表红绿灯*/
ul>li {
width: 40px;
height: 40px;
border-radius: 50%;
opacity: 0.2;
display: inline-block;
}
/*执行时改变透明度*/
ul.red>#red,
ul.green>#green,
ul.yellow>#yellow {
opacity: 1.0;
}
/*红绿灯的三个颜色*/
#red {
background: red;
}
#yellow {
background: yellow;
}
#green {
background: green;
}
</style>
</html>
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/149737.html