js写一个亮灯逻辑依次为: 红色显示3秒 绿色显示2秒 黄色显示1秒 三种颜色循环交替显示,要求使用 Promise 实现 页面样式 编写一个显示红绿灯的 HTML 页面,要求使用纯 CSS 实现
时间: 2024-03-10 13:48:02 浏览: 16
好的,下面是使用 Promise 实现的亮灯逻辑代码:
```
function light(color, duration) {
return new Promise(function(resolve) {
console.log(color + '灯亮起来了');
setTimeout(function() {
console.log(color + '灯熄灭了');
resolve();
}, duration);
});
}
function run() {
light('红', 3000)
.then(function() {
return light('绿', 2000);
})
.then(function() {
return light('黄', 1000);
})
.then(function() {
return run();
});
}
run();
```
这段代码定义了一个 `light` 函数,用来亮起和熄灭各种颜色的灯,并返回一个 Promise 对象。然后定义了一个 `run` 函数,通过不断地调用 `light` 函数来实现循环交替显示三种颜色的灯。最后调用 `run` 函数启动整个亮灯逻辑。
下面是使用纯 CSS 实现的红绿灯 HTML 页面样式:
```html
<!DOCTYPE html>
<html>
<head>
<title>红绿灯</title>
<style>
.light {
width: 100px;
height: 100px;
border-radius: 50%;
background-color: gray;
position: relative;
margin: 50px auto;
}
.light .circle {
width: 80px;
height: 80px;
border-radius: 50%;
background-color: black;
position: absolute;
top: 10px;
left: 10px;
}
.light .red {
background-color: red;
animation: blink 3s infinite;
}
.light .yellow {
background-color: yellow;
animation: blink 1s infinite;
animation-delay: 3s;
}
.light .green {
background-color: green;
animation: blink 2s infinite;
animation-delay: 4s;
}
@keyframes blink {
50% {
opacity: 0.5;
}
}
</style>
</head>
<body>
<div class="light">
<div class="circle red"></div>
<div class="circle yellow"></div>
<div class="circle green"></div>
</div>
</body>
</html>
```
这段代码定义了一个 `light` 类,包含一个 `init` 方法和一个 `run` 方法。`init` 方法用来初始化红绿灯的状态,`run` 方法用来循环交替显示三种颜色的灯。在 HTML 页面中创建一个 `div` 元素作为灯的外框,然后在其中创建三个 `div` 元素作为灯的圆形,通过设置各个元素的样式和动画,实现红绿灯的效果。