减少jQuery颜色动画的加载时间

Reduce load time on jQuery color animation

本文关键字:加载 时间 动画 jQuery 颜色 减少      更新时间:2023-09-26

我试图让每个跨度以 3 秒的间隔在随机颜色之间旋转。

JSFiddle: http://jsfiddle.net/WERFJ/21/

<h1><span class="first">TEXT1</span> <span class="second">TEXT2</span> <span class="third">TEXT3</span></h1>

目前我正在使用下面的代码和jquery.animate-colors插件。有没有办法使这个运行或更快地获得相同的效果。Chrome可以处理它,但FF经常崩溃。谢谢!

$(document).ready(function() {  
        spectrum();  
            function spectrum(){  
                var hue1 = 'rgb(' + 128 + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
                var hue2 = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + 128 + ',' + (Math.floor(Math.random() * 256)) + ')';  
                var hue3 = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + 128 + ')';  
                $('.first').animate( { color: hue1 }, 3000);
                $('.second').animate( { color: hue2 }, 3000);
                $('.third').animate( { color: hue3 }, 3000); 
                spectrum();  
        }  
    });

我认为您的问题是递归调用没有等待动画完成。 通过将调用作为回调添加到最后一个 Animate 调用中,您将仅在最后一个调用完成时调用它,而不是排队和无限的动画链。 http://jsfiddle.net/WERFJ/23/它现在似乎在火狐中工作正常

$(document).ready(function() {
    spectrum();
    function spectrum() {
        var hue1 = 'rgb(' + 128 + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
        var hue2 = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + 128 + ',' + (Math.floor(Math.random() * 256)) + ')';
        var hue3 = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + 128 + ')';
        $('.first').animate({
            color: hue1
        }, 3000);
        $('.second').animate({
            color: hue2
        }, 3000);
        $('.third').animate({
            color: hue3
        }, 3000, spectrum);
    }
});​

从用户的角度来看,最初的延迟是因为浏览器不会更新显示,直到您的函数完成运行,但您的函数只是递归地调用自己,直到出现堆栈溢出 - 或者,在 FF 中我得到了"太多递归"错误。只有在"太多递归"错误使函数崩溃之后,所有排队的动画才真正开始工作。

您可以通过更改函数的最后一行来避免这种情况,以使用 setTimeout() 对另一个调用进行排队,而不是让它直接调用自身:

setTimeout(spectrum,3100);

http://jsfiddle.net/WERFJ/24/

使用 $.when 包装动画,then()运行下一个系列。 然后,jQuery 延迟对象确保所有动画在重新开始之前都已完成

演示:http://jsfiddle.net/WERFJ/26/

var anim_1 = $('.first').animate({ color: hue1}, 3000);
var anim_2 = $('.second').animate({color: hue2}, 3000);
var anim_3 = $('.third').animate({color: hue3}, 3000);
$.when(anim_1, anim_2, anim_3).then(spectrum);