2013-07-09 28 views
1

我试图创建一个动画滑块,来回显示图像和动画,除非鼠标悬停,它暂停鼠标悬停,需要继续鼠标离开。我创造了这个,但当鼠标离开时有一些愚蠢的问题,动画只会完成一个循环。一些帮助。 下面是代码:动画滑块不继续鼠标离开

jQuery.fn.makeScroller = function(options){ 
    var defaults = { 
     hoverStop : true 
    }; 
    var options = jQuery.extend(defaults, options); 

    obj = this; 

    var scrollWrapWidth = 0; 
    obj.children().each(function(){ scrollWrapWidth += $(this).width(); }); 

    scrollWrapper = jQuery('<div/>',{class:"scrollWrapper", style:"width:"+scrollWrapWidth+"px"}); 

    obj.children().wrapAll(scrollWrapper); 
    function animateThis(obj, dist, time){ 
     obj.animate({marginLeft: dist}, { 
      duration:time, 
      complete:function(){ 
       obj.animate({marginLeft: "0"}, { 
        duration:time, 
        complete:function(){ 
         animateThis(obj, dist, time); 
        } 
       }) 
      } 
     }); 
     obj.hover(function(){ 
      obj.stop(true); 
     }, function(){ 
      animateThis(obj, dist, time); 
     }); 
    }; 

    widthDiff = (scrollWrapWidth - obj.width()) * -1; 
    animateThis(obj.children(".scrollWrapper"), widthDiff, 3000); 
} 
jQuery(document).ready(function(){ 
    id = ".myScroller"; 
    jQuery(id).makeScroller(); 
}); 

这里是我创造了你发现问题的小提琴链接 - http://jsfiddle.net/cruising2hell/YvNR6/4/

感谢

回答

1

添加

obj.stop(true); 

以上

animateThis(obj, dist, time); 

解决了这个问题。

obj.hover(function(){ 
     obj.stop(true); 
    }, function(){ 
     obj.stop(true); 
     animateThis(obj, dist, time); 
    }); 
1

我相信你的问题可能涉及到的事实,你重新绑定到动画完成回调的内部mouseentermouseleave事件(通过hover()方法)。第一次鼠标悬停时,一个mouseenter事件将会触发,下一次会发生两次,然后是三次等。这会对性能造成震动,并导致一些非常奇怪的行为。

我建议移动事件绑定离开那里,就像沿着这些路线的东西:

obj.children().wrapAll(scrollWrapper); 

function animateThis(obj, dist, time) { 
    obj.animate (
     { marginLeft: dist }, 
     { 
      duration:time, 
      complete: 
       function() { 
        obj.animate (
         { marginLeft: "0" }, 
         { 
          duration:time, 
          complete:function() { 
           animateThis(obj, dist, time); 
          } 
         } 
        ) 
       } 
     } 
    ); 
}; 

widthDiff = (scrollWrapWidth - obj.width()) * -1; 

function resumeAnimation() { 
    animateThis(obj.children(".scrollWrapper"), widthDiff, 3000); 
}; 

resumeAnimation(); 

obj.hover(
     function() { 
      obj.children(".scrollWrapper").stop(true, false); 
     }, 
     function() { 
      resumeAnimation(); 
     } 
    ); 

JS小提琴这里:http://jsfiddle.net/YvNR6/12/

相关问题