2013-07-09 30 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/

相關問題