在JQuery中鼠标悬停和鼠标移动时停止和继续动画的方法

时间:2011-02-23 08:56:59

标签: jquery animation hover

E.g:

一个简单的例子来解释:

$('.moveDiv').animate({ "margin-left": 2000 }, 20000, 'linear');

moveDiv element在加载时会向左移动,现在,当mouse move over moveDiv element时,我希望它在mouse move out时停止并继续移动}!

有什么想法吗?

我在这个question of stackoverflow中找到了这个代码,所以,我只是想修改代码,以便在鼠标悬停时可以停止并继续动画!!

the demo of the code

3 个答案:

答案 0 :(得分:8)

Pause / Resume Animation Plugin

    $(document).ready(function () {

        $(".moveDiv")
        .mouseover(function () { $(this).pauseAnimation(); })
        .mouseout(function () { $(this).resumeAnimation(); })
        .startAnimation({ "margin-left": 2000 }, 20000, 'linear');

    });

答案 1 :(得分:0)

尝试:

$('.moveDiv')
    .animate({ "margin-left": 2000 }, 20000, 'linear')
    .hover(function(){
        $(this).stop(true,false);
    },
    function(){
        $(this).animate({ "margin-left": 2000 }, 20000, 'linear')
    });

让我知道你是怎么过的......

oops .stop(true,false);

答案 2 :(得分:0)

刚刚找到了EBCEu4解决方案中建议的插件 - 问题使用但是可重复使用的解决方案将是:

var duration = 5000;
var target = 200;
$('.moveDiv')
    .animate({ "margin-left": target }, duration, 'linear')
    .hover(
     function(){
        $(this).stop(true,false);
    },
    function(){
        var $this = $(this);
        var cur = parseInt($this.css('margin-left'));
        $this.animate({ "margin-left": target }, duration*((target-cur)/target), 'linear')
    });