The way to stop and continue animation while mouse

2019-01-15 17:09发布

问题:

E.g:

a simple example to explain:

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

the moveDiv element would move to left when it was loaded,and now, when the mouse move over the moveDiv element, I wish it to stop and continue to move when the mouse move out!

Any ideas?

I found this code in this question of stackoverflow,so , I just want to modify the code to make it could stop and continue animation when mouse hover!!

the demo of the code

回答1:

Pause / Resume Animation Plugin

    $(document).ready(function () {

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

    });


回答2:

Try:

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

let me know how you get on...

oops .stop(true,false);



回答3:

Just found the plugin suggested in EBCEu4's solution - prob use that but the far-less reuseable solution would be:

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')
    });