要素の背景色をフェードするスクリプトを作成しました。setTimeout()を使用して、5ミリ秒ごとに色を段階的に変更します。スクリプトは、一度に1つのものの背景色をフェードするだけの場合はうまく機能しますが、たとえば、一度に50個の要素をフェードする場合、速度は5ミリ秒よりもはるかに遅くなります。同時に実行されているsetTimeout()。たとえば、通常1秒で実行されるはずのフェードは、一度に50個の要素をフェードする場合、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);