如何在jQuery中停止动画,但首先完成动画

时间:2012-04-18 13:58:53

标签: javascript jquery slider jquery-animate

我需要自动滑块动画的帮助。所以,我的问题是 - 如何在悬停事件中停止动画,但不是立即停止,而是在单独元素上的动画完全结束时停止。

我有这段代码:

$(function(){

   var current_slide=1;
   var set_time=2500;

   $('span').css({top:'300px'});

   $.timer(6000,function(timer){
      switch(current_slide){
         case 1:
            $('span').css({top:'350px'});
            $('#slideshow').stop().animate({left:'-960px',top:'0px'},{easing:'easeOutBack',duration:set_time});
            current_slide=2;
            $('span').delay(2500).animate({top:'300px'});
            break;
         case 2:
            $('span').css({top:'350px'});
            $('#slideshow').stop().animate({left:'-1920px',top:'0px'},{easing:'easeOutBack',duration:set_time});
            current_slide=3;
            $('span').delay(2500).animate({top:'300px'});
            break;
         case 3:
            $('span').css({top:'350px'});
            $('#slideshow').stop().animate({left:'-2880px',top:'0px'},{easing:'easeOutBack',duration:set_time});
            current_slide=4;
             $('span').delay(2500).animate({top:'300px'});
            break;

         case 4:
            $('span').css({top:'350px'});
            $('#slideshow').stop().animate({left:'0px',top:'0px'},{easing:'easeOutExpo',duration:set_time});
            current_slide=1;
            $('span').delay(2500).animate({top:'300px'});
            break;
      }

      timer.reset(12000);
   });

   $("#slideshow").hover(function(){
      $(this).stop(true,true);
   });
});

麻烦在于我将鼠标悬停在滑块上,然后动画停止(跳到最后)几乎,突然和丑陋。可能我应该在.stop()之前使用队列,或类似的东西。 这是一个很好的例子:http://www.sevtopolishotel.com/ Tnx提前!

3 个答案:

答案 0 :(得分:1)

您可以像这样跟踪悬停状态:

var isHovered = false;
$("#slideshow").hover(function(e){
    isHovered = e.type == 'mouseenter';
});

从那里,可以将整个开关包裹在if(!isHovered) { ... }中,这意味着只要幻灯片悬停,计时器就会立即跳到设置下一次超时。

答案 1 :(得分:0)

这是.stop()文档:http://api.jquery.com/stop/

在那里写的是你可以传递“jumpToEnd”的参数。如果该参数为false,则动画将继续直到结束。我认为你的代码应该是这样的:

$("#slideshow").hover(function(){
          $(this).stop(true,false);
    });  });

答案 2 :(得分:0)

您可以保留对计时器的引用。然后,而不是停止动画,你只需清除计划动画的计时器。所以当前的动画将会进行,但没有一个会被安排再次运行。 如果您使用的是javascript setTimeout,则可以执行此操作

vat timer=setTimeout(animation_function, delay);
 //to stop later
clearTimeOut(timer);

但我认为你正在使用jquery计时器插件仍然你的$ .timer插件应该有一个明确的方法来停止再次运行检查文件。

看看这个Post几乎是同一个问题。