我创建了一个淡化元素背景颜色的脚本。我使用 setTimeout() 每 5 毫秒对颜色进行一次增量更改。如果我一次只淡化一件事的背景颜色,该脚本效果很好,但如果我有 50 个元素,我会一次全部淡化,速度比 5 毫秒慢得多,因为所有同时运行的 setTimeout()s。例如,如果我一次淡化 50 个元素,通常应该在 1 秒内执行的淡入淡出可能需要 30 秒。
有什么想法可以克服这个问题吗?
如果有人有想法,这是脚本:
function fadeBackground(elementId, start, end, time) {
var iterations = Math.round(time / 5);
var step = new Array(3);
step[0] = (end[0] - start[0]) / iterations;
step[1] = (end[1] - start[1]) / iterations;
step[2] = (end[2] - start[2]) / iterations;
stepFade(elementId, start, step, end, iterations);
}
function stepFade(elementId, cur, step, end, iterationsLeft) {
iterationsLeft--;
document.getElementById(elementId).style.backgroundColor
= "rgb(" + cur[0] + "," + cur[1] + "," + cur[2] + ")";
cur[0] = Math.round(end[0] - step[0] * iterationsLeft);
cur[1] = Math.round(end[1] - step[1] * iterationsLeft);
cur[2] = Math.round(end[2] - step[2] * iterationsLeft);
if (iterationsLeft > 1) {
setTimeout(function() {
stepFade(elementId, cur, step, end, iterationsLeft);
}, 5);
}
else {
document.getElementById(elementId).style.backgroundColor
= "rgb(" + end[0] + "," + end[1] + "," + end[2] + ")";
}
}
它是这样使用的:
fadeBackground("myList", [98,180,232], [255,255,255], 1000);