2014-03-05 177 views
3

我正在为一个滚动div设置动画,并且已经能够触发点火,滚动,并在点击和/或鼠标停止时停止。现在,当鼠标悬停在div而不是停止时,我想让它暂停。我是一个总jquery newb,所以我真的不知道什么会工作,什么不会。这是我的代码到目前为止,它工作正常。暂停滚动悬停

$(document).ready(function() { 
    var sL = 4000; 
    $('.scrolls').animate({ 
     scrollLeft : sL 
    },100000, 'linear'); 

    $(".scrolls").on("click",function(){ 
     $(this).stop(true,false); 
    }); 

}) 

任何帮助都非常赞赏!

谢谢!

http://jsfiddle.net/BMb65/9/

+1

查找到'queue'和'dequeue'在jQuery的文档 –

+0

谢谢!我已经研究过它,但还没有弄清楚如何把它放在一起。它似乎应该很容易,但是当然...我可以简单地与.dequeue交换.stop还是必须完全重新配置代码?这是一个jsfiddle http://jsfiddle.net/BMb65/9/ – user3158649

+0

我为您的代码编写了一个修改后的版本,可根据需要进行工作。请回顾下面我的答案.. –

回答

1

这应该工作:

$(document).ready(function() { 
    var $div = $('.scrolls'); 
    var sL = 4000; 
    var startTime = new Date().valueOf(); 
    var timePassed; 
    var stopped = false; 
    //animate: 
    $div.animate({ 
     scrollLeft : sL 
    },100000, 'linear'); 

    //on click, stop animation: 
    $div.on("click",function(){ 
     $div.stop(true,false); 
     stopped = true; 
    }); 

    //on mouseover -> stop animation (pause) 
    //on mouseout -> resume animation (actually a new animation 
    $div.hover(function() { //mouseenter 
     $div.stop(true, false); 
     timePassed = (new Date()).valueOf() - startTime; 
    }, function() { //mouseleave 
     if (!stopped) { //resume only if it was stopped on mouse enter, not on click 
      $div.animate({ 
       scrollLeft : sL 
      }, 100000 - timePassed, 'linear'); 
     } 
    }); 
}); 

有了这个代码,当你将鼠标悬停在DIV,动画停止。我们记录自启动以来经过了多少时间,因此我们可以创建一个新动画,通过将其持续时间设置为原来的持续时间减去已经过去的时间来模拟恢复旧动画。

希望这会有所帮助。

+1

我已经更新你的小提琴工作解决方案:http://jsfiddle.net/BMb65/10/ –

+0

这工作完美!谢谢! – user3158649

+0

很高兴能有所帮助。请标记答案是正确的。 –

1

为什么不使用的mouseenter和鼠标离开事件..

请检查此琴指出: Modified Code

基本上,你会做这样的事情:

$(".scrolls").on("mouseenter",function(){ 
    $(this).stop(true,false); 
}); 

$(".scrolls").on("mouseleave",function(){ 
    $(this).animate({ 
    scrollLeft : sL 
    },100000, 'linear'); 
}); 
1

请看看这个小提琴http://jsfiddle.net/93Ta8/

我所做的只是利用

$(".scrolls").on("mouseenter" 

$(".scrolls").on("mouseleave"