4

我遇到了 setInterval 和 jquery animate 的问题。这是我的代码:

function slides1() {

    ...

    $("table#agah1").animate({
        "left": first1
    }, "slow");
    $("table#agah2").animate({
        "left": first2
    }, "slow");
}

$(function () {
    cyc = setInterval("slides1()", 3000);
});

当切换到另一个浏览器选项卡并在一段时间后返回时,动画会毫不拖延地继续执行,直到我离开该选项卡的时间,然后才能正确操作。我添加了这些也没有任何运气:

$(window).focus(function () {
    jQuery.fx.off = false;
    cyc = setInterval("slides1()", 3000);
});
$(window).blur(function () {
    jQuery.fx.off = true;
    window.clearInterval(cyc);
});
4

1 回答 1

4

较新版本的 jQuery 使用requestAnimationFrame回调来处理效果,浏览器不会处理隐藏选项卡上的效果。

与此同时,您的setInterval事件仍在发生,导致更多动画排队。

与其用来安排动画,不如使用setInterval上一个动画的“完成回调”来触发下一个循环,setTimeout如果需要的话。

function slides1() {

    ...

    $("table#agah1").animate({
        "left": first1
    }, "slow");
    $("table#agah2").animate({
        "left": first2
    }, "slow", function() {
       setTimeout(slides1, 2000); // start again 2s after this finishes
    });
}

$(function () {
    setTimeout(slides1, 3000);    // nb: not "slides1()"
});

这将确保动画间延迟和动画本身之间存在紧密耦合,并避免setTimeout与动画不同步的任何问题。

于 2012-05-20T06:35:14.700 回答