2

我有一个简单的动画淡入和淡出无序列表中的每个列表项。HTML 标记如下:

<ul>
  <li>first par</li>
  <li>second par</li>
  <li>third par</li>
</ul>

<div></div>

空 div 将包含通过 jquery 动态地导航控件的按钮。

脚本如下:

<script>

var ul = $('ul'), li = $('ul li'), li_length = li.length, div = $('div');

//hides all list items
li.hide();

function play (eq){
  eq = (eq===undefined) ? 0 : eq; 

  for(i=eq, d=0; i<li_length; i++, d+=3000){
    li.eq(i).delay(d).fadeIn(1000).delay(1000).fadeOut(1000);
  }
}

//This dynamically appends the nav buttons in the div
li.each(function(i){
  div.append('<button> '+ i + '</button>');
})

//the normal animation going through each list item, fading in and out
play();

var btn = $('div button');

//each button when clicked should animate the corresponding list item (fadein and out), then the next 
li.each(function(i){
   btn.eq(i).click(function(){
     li.stop(true, true);
     li.hide();
     play(i);
   })
})

</script>

运行时play(),它完成了工作。但是,当您单击任何导航按钮时,例如正在播放第二个列表项,然后单击按钮 1(基本上调用play(1)),play()尽管我已经停止使用.stop(). 结果是重叠的动画。我是一个菜鸟,对如何处理这个问题一无所知,这样动画就不会重叠。任何人都可以帮忙吗?

4

1 回答 1

0

delay无论您停止当前动画,都将继续运行:

.delay() 方法最适合在排队的 jQuery 效果之间进行延迟。因为它是有限的——例如,它不提供取消延迟的方法——.delay() 不能替代 JavaScript 的原生 setTimeout 函数,这可能更适合某些用例。

而不是delay你应该setTimeout在你的处理程序中使用和取消它click

var timeoutId = setTimeout(function() { [fadeIn/fadeOut] }, delayDuration);

然后从您的click处理程序:

btn.eq(i).click(function() {
    ...
    clearTimeout(timeoutId);
});

play设置运行的方式,您需要为每个li动画设置和取消超时。

修正

使用setTimeout,您的一些代码可以重写如下:

function play (eq){
    var
        eq = eq || 0,
        i, d; 

    for(i=eq, d=0; i<li_length; i++, d+=3000){

        // store the timeoutID returned by setTimeout on the li itself
        li.data('timeoutId', setTimeout(function() {
                li.eq(i).fadeIn(1000).delay(1000).fadeOut(1000);
            }, d)
        );
    }
}

然后在您的click处理程序中:

li.each(function(i){
    btn.eq(i).click(function(){
        li.stop(true, true);
        li.hide();

        // grab the timeoutId and clear it
        clearTimeout(parseInt(li.data('timeoutId'), 10));

        play(i);
    });
});

您可能需要对 / 之间的额外调用setTimeout,但delay希望您从上面的代码中明白了这一点。fadeInfadeOut

于 2013-07-15T11:32:10.977 回答