效果
代码
-
html
<div class="traffic"> <div class="light"></div> </div>
-
css
.traffic { margin: 2rem; background-color: #005E5D; width: 40px; height: 60px; border-radius: 15px;/*圆角*/ display: flex; justify-content: center; /*主轴对齐居中*/ align-items: center; /*交叉轴对齐居中*/ box-shadow: 4px -2px;/*阴影*/ } .light { width: 1.5rem; height: 1.5rem; border-radius: 100%;/*圆角*/ background-color: #EE464A; }
-
js
var setColor = function (color) { document.getElementsByClassName("light")[0].style.backgroundColor = color; } var setTime = function (timer) { return function () { return new Promise(function (resolve, reject) { setTimeout(resolve, timer); }); } } let keepgreen = setTime(3000); let keepyellow = setTime(4000); let keepred = setTime(5000); (function start() { let red = '#EE464A', green = '#B0CA4B', yellow = '#F7D309'; setColor(green); keepgreen() .then(function () { setColor(yellow); return keepyellow(); }) .then(function () { setColor(red); return keepred(); }) .then(function () { start(); }) })()
居中显示
display: flex;
justify-content: center;
/*主轴对齐居中*/
align-items: center;
/*交叉轴对齐居中*/
- 父元素选择flex布局,子元素在主轴和交叉轴上的对齐方式都是居中,从而实现水平垂直居中
声明函数立刻调用
(function start() {
……
})()
- IIFE(Immediately Invoked Function Expression)
- 在函数声明外面包裹()→函数声明变成函数表达式 → 后面再加一个()立即调用
js操作dom
var setColor = function (color) {
document.getElementsByClassName("light")[0].style.backgroundColor = color;
}
- 根据传入参数值修改div.light背景颜色
promise使用
var setTime = function (timer) {
return function () {
return new Promise(function (resolve, reject) {
setTimeout(resolve, timer);
});
}
}
let keepgreen = setTime(3000);
let keepyellow = setTime(4000);
let keepred = setTime(5000);
- keepgreen、keepyellow、keepred被赋值为函数,且该函数可以创建promise对象
- 当异步代码执行成功时,调用resolve(...)
(function start() {
let red = '#EE464A', green = '#B0CA4B', yellow = '#F7D309';
setColor(green);
keepgreen()
.then(function () {
setColor(yellow);
return keepyellow();
})
.then(function () {
setColor(red);
return keepred();
})
.then(function () {
start();
})
})()
- 已经实例化过的 promise 对象(keepgreen()、keepyellow()、keepred())可以调用 promise.then() 方法,传递 resolve 和 reject 方法作为回调。