cor*_*ore 5 javascript settimeout
我创建了一个淡化元素背景颜色的脚本.我使用setTimeout()每5毫秒对颜色进行一次增量更改.如果我只是一次淡化一件事的背景颜色,那么该脚本效果很好,但如果我有50个元素,我一下子都褪色,速度比5毫秒慢得多,因为所有并发setTimeout()一次运行.例如,如果我一次褪色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] + ")";
}
}
Run Code Online (Sandbox Code Playgroud)
它的使用方式如下:
fadeBackground("myList", [98,180,232], [255,255,255], 1000);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4099 次 |
| 最近记录: |