1 回答
TA贡献1865条经验 获得超7个赞
您只需要查询要闪烁的类并遍历每个元素。我还更改为 switch 语句而不是 if 语句,并进行了一些格式化和更改,使其flash不是全局变量。
function lightning(className, flash = 1) {
const flashes = {
1: { color: "white", delay: 100 },
2: { color: "black", delay: 90 },
3: { color: "red", delay: 85 },
4: { color: "blue", delay: 80 },
5: { color: "purple", delay: 75 },
6: { color: "white", delay: 70 },
7: { color: "black", delay: 65 },
8: { color: "red", delay: 60 },
9: { color: "blue", delay: 50 },
10: { color: "purple", delay: 40 },
11: { color: "black", delay: 30 },
12: { color: "white", delay: 25 },
13: { color: "red", delay: 20 },
14: { color: "blue", delay: 10 },
15: { color: "purple", delay: 5 },
16: { color: "white", delay: 1 },
17: { color: "black", delay: 1 },
18: { color: "blue", delay: 1 },
19: { color: "purple", delay: 1 }
};
switch (flash) {
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
Array.from(document.getElementsByClassName(className)).forEach(
el => (el.style.backgroundColor = flashes[flash].color)
);
setTimeout(() => lightning(className, flash + 1), flashes[flash].delay);
case 20:
setTimeout(() => lightning(className), 100);
}
}
setTimeout(() => lightning("my-class-name"), 1);
更新:更简单的代码几乎可以做同样的事情(延迟/颜色与原始代码中的 100% 不同):
function lightning(className, flash = 1) {
const color = i => {
switch (i % 5) {
case 1:
return "white";
case 2:
return "red";
case 3:
return "blue";
case 4:
return "purple";
case 0:
return "black";
}
};
if (flash > 0 && flash < 20) {
Array.from(document.getElementsByClassName(className)).forEach(
el => (el.style.backgroundColor = color(flash))
);
setTimeout(() => lightning(className, flash + 1), 100 - flash * 5);
} else {
setTimeout(() => lightning(className), 100);
}
}
setTimeout(() => lightning("my-class-name"), 1);
添加回答
举报