【问题标题】:setTimeout and animation issuesetTimeout 和动画问题
【发布时间】:2011-08-14 21:34:09
【问题描述】:

请帮忙! 我有一个奇怪的问题。

DEMO

此库中的问题是,如果您将鼠标悬停/鼠标移出快速DURING动画
比画廊变得“疯狂”,表现得像 .animate() 正在与 setTimeout 战斗。

AFAIK - 你不能在这里使用 setInterval,因为如果你从另一个“标签”返回到画廊,画廊的行为就像它会立即补偿所有动画(在不活动期间)。

请帮助我了解此问题并找到解决方法。
提前致谢!

用于胆的代码:

var galW = $('#gallery').width(),
    imgN = $('#slider img').length,
    c = 1,   // counter
    timeOut,
    pause = false;

$('#slider').width(galW * imgN);

function auto() {
    if (pause) { return; }                        // if hovered : stop 'timeOut'
    timeOut = setTimeout(function() {
        c++;
        if (c === (imgN + 1)) {
            c = 1;
        }
        $('#slider').animate({left: '-' + galW * (c - 1) + 'px'}, 1200, auto);
    }, 1900);
}
auto();

$('#galcontainer').hover(function() {
    pause = true;
    clearTimeout(timeOut);
}, function() {
    pause = false;
    auto();
});

【问题讨论】:

    标签: jquery animation gallery jquery-animate settimeout


    【解决方案1】:

    看看这个

    http://jsfiddle.net/8Lzxs/3/

    var galW = $('#gallery').width(),
        imgN = $('#slider img').length,
        c = 1,   // counter
        timeOut,
        pause = false;
    
    $('#slider').width(galW * imgN);
    
    function auto() {
        if (pause) { return; }                       
        clearTimeout(timeOut);               // THE (added) FIX !!!!!!!!! //
        timeOut = setTimeout(function() {
            c++;
            if (c === (imgN + 1)) {
                c = 1;
            }
            $('#slider').animate({left: '-' + galW * (c - 1) + 'px'}, 1200, auto);
        }, 1900);
    }
    auto();
    
    $('#galcontainer').hover(function() {
        pause = true;
        clearTimeout(timeOut);
    }, function() {
        pause = false;
        auto();
    });
    

    【讨论】:

    • 这看起来像是我寻找 2 天的答案。 +1香卡尔!非常感谢!你能解释一下你是怎么想到这个想法的吗? (在调用之前清除timeOut?)
    • 当动画正在进行时,有时 mouseout 事件不会被触发,因此 pause 没有设置为 false。因此,在下一个 mouseoever 事件中,由于 pause 不是 false,它将再次设置超时。我只是确保我们清除了之前的任何超时。
    • @roXon - 链接在哪里,我会马上去解释:)
    猜你喜欢
    • 1970-01-01
    • 2015-01-27
    • 2021-02-09
    • 2011-10-30
    • 1970-01-01
    • 2018-02-17
    • 2011-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多