jQuery多个动画并跟踪他们的进度

时间:2013-03-11 15:54:05

标签: jquery jquery-animate

我正在编写一个包含许多动画的脚本,这些动画以并行和不同的顺序发生。根据网页上点击的内容,使用一组特定的动画。这些功能被重复使用,并且每次都不会以相同的顺序出现。

当用户单击另一个元素而不让第一组动画完成时,会出现问题。在这种类型的实例中,脚本会中断并无法按预期运行。这显然是因为没有完成进展并且开始执行另一组动画。

我的问题是,是否有任何练习来确定当前是否正在运行动画,以防止在当前设置完成之前执行另一组动画。

3 个答案:

答案 0 :(得分:1)

您可以使用:animated选择器:

if ($("yourSelector:animated").length > 0) {
    // Some of the elements matching 'yourSelector' are still being animated.
}

或者,您可以在开始新动画之前调用finish()以强制立即完成当前动画:

$("yourElement").finish().animate({
    // The properties to animate...
});

答案 1 :(得分:1)

如果您只想在开始新动画之前确保与特定元素关联的动画正常完成,则可以使用.queue()功能。 See my example on jsFiddle

$( function() {
    $(".clicker").on("click", function() {
        var self = $(this);
        self.queue( function(next) {
            self.animate({left:"+=100"}, 1000); // Replace with your animation
            next();
        });
    });
});

Read more about the queue function on api.jquery.com

答案 2 :(得分:0)

jQuery还有一个名为$.timers的隐藏暴露变量,其中包含当前动画/等所有内容的数组。在速度方面速度非常快,性能方面你不希望循环遍历$('*').is(':animated'),以测试页面上是否有任何东西在移动。

我创建了一个小函数,它一遍又一遍地循环遍历它们全部完成,然后执行回调函数。

function isPageAnimated (_func) {    
    var testAnimationInterval = setInterval(function () {
        if ($.timers.length === 0) { // any page animations finished
            clearInterval(testAnimationInterval);
            _func(); // callback function
        }
    }, 100);
}
相关问题