需求: 用js实现红绿灯效果。
三个状态用红(stop)、绿(pass)、黄(wait)
要求用JavaScript让三个状态轮流切换,每个状态停留2s
HTML
<ul id="traffic" class="stop" >
<li><span></span></li>
<li><span></span></li>
<li><span></span></li>
</ul>
CSS
li{
list-style: none;
}
ul li span{
display: inline-block;
width: 50px;
height: 50px;
background-color: gray;
margin: 5px;
border-radius: 50%;
}
#traffic.stop li:nth-child(1) span{
background-color: red;
}
#traffic.wait li:nth-child(2) span{
background-color: yellow;
}
#traffic.pass li:nth-child(3) span{
background-color: green;
}
JavaScript实现
版本1
缺点:依赖外部变量stataList,currentIndex, 封装性差了点
const traffic = document.getElementById('traffic');
const statusList = ['stop', 'wait', 'pass'];
var curentIndex=0;
setInterval(() => {
let state = statusList[curentIndex];
traffic.className = state;
curentIndex = (curentIndex+1) % statusList.length;
}, 2000);
版本2 数据抽象
缺点:比版本1好点,不过扩展性较差
const traffic = document.getElementById('traffic');
const stateArr = ['stop', 'wait', 'pass'];
function trafficFn(trafficDom, stateList){
let currentIndex = 0;
setInterval( ()=>{
const state = stateList[currentIndex];
trafficDom.className = state;
currentIndex = (currentIndex+1) % stateList.length;
}, 2000 )
}
trafficFn( traffic, stateArr );
版本3 函数式编程, 抽象出poll方法
const traffic = document.getElementById('traffic');
// const statusList = ['stop', 'wait', 'pass'];
function poll(...fnList){
let stateInex = 0;
return function(...args){
let fn = fnList[stateInex++ % fnList.length];
return fn.apply(this, args);
}
}
function setState(state){
traffic.className = state;
}
// 循环执行这三个函数
let trafficStatePoll = poll(
setState.bind(null, 'wait'),
setState.bind(null, 'stop'),
setState.bind(null, 'pass')
)
setInterval(trafficStatePoll, 2000);
2.简单的深拷贝
function deepCopy(obj) {
const res = obj instanceof Array ? [] : {};
for(key in obj) {
res[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
}
return res;
}
3.使用Promise异步加载一个图片
function loadImg(url) {
return new Promise((resolve, reject) => {
const image = new Image();
image.src = url;
image.onload = () => {
resolve(image);
};
image.onerror = reject;
document.body.append(image);
})
}
loadImg('hao123.com').then((image)=>{
image.style.border = '6px solid red';
}).catch((e)=>{
console.log('加载失败了', e);
})