<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>红绿灯</title>
<style>
#box {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
background-color: black;
opacity: 0.8;
}
#green,
#yellow,
#red {
width: 50px;
height: 50px;
border-radius: 50%;
margin: 10px;
}
#green {
background-color: green;
opacity: 0.2;
}
#yellow {
background-color: yellow;
opacity: 0.2;
}
#red {
background-color: red;
opacity: 0.2;
}
#box {
width: 250px;
height: 60px;
}
</style>
</head>
<body>
<div id="box">
<!-- 三个圆 -->
<div id="green"></div>
<div id="yellow"></div>
<div id="red"></div>
</div>
<script>
//封装
function green() {
return new Promise(function (resolve, reject) {
setTimeout(() => {
resolve();
console.log("1");
document.querySelector("#red").style.opacity = "0.1";
document.querySelector("#green").style.opacity = "1";
}, 3000);
});
}
function yellow() {
return new Promise(function (resolve, reject) {
setTimeout(() => {
resolve();
console.log("2");
document.querySelector("#green").style.opacity = "0.1";
document.querySelector("#yellow").style.opacity = "1";
}, 3000);
});
}
function red() {
return new Promise(function (resolve, reject) {
setTimeout(() => {
resolve();
console.log("3");
document.querySelector("#yellow").style.opacity = "0.1";
document.querySelector("#red").style.opacity = "1";
}, 3000);
});
}
async function fn() {
await green();
await yellow();
await red();
fn();
}
fn();
</script>
</body>
</html>
原生js使用async和await制作红绿灯
最新推荐文章于 2024-06-16 16:43:26 发布