开发者

How to stop all previous animations in jQuery before executing new one?

I am just experimenting something with jQuery.

I have an image which fades into another image as mouseOver() occurs and fades back on mouseOut()

It works great, except if you are moving your mouse over the开发者_StackOverflow中文版 link again and again, say 5 times, the image fades in and out repeatedly, 5 times while you just sit there and wait for it to get over with this crazy behaviour.

To stop this behaviour, I tried to use a flag and start the animation ONLY if it isn't already animating, but, guess what? If, say, I have 4 such buttons, and on each button mouseover I am fadingIn a different image, that animation will be ignored since the flag is false.

So is there a way to stop all the previous animations before executing new ones? I am talking about the normal fadeIn() and slideDown() functions in JQuery


EDIT: Adding code from link.

<a href="javascript:void(0);" onMouseOver="mouseOverOut(false);" onMouseOut="mouseOverOut(true);">Tick</a>

JavaScript

function mouseOverOut(t)
{
    if(t)
    {
        $('.img1').fadeIn();
        $('.img2').fadeOut();
    }
    else
    {
        $('.img1').fadeOut();
        $('.img2').fadeIn();
    } 
}


Using .stop() with fadeIn/Out can cause the opacity to get stuck in a partial state.

One solution is to use .fadeTo() instead, which gives an absolute destination for the opacity.

function mouseOverOut(t) {
    if(t) {
        $('.img1').stop().fadeTo(400, 1);
        $('.img2').stop().fadeTo(400, 0);
    }
    else {
        $('.img1').stop().fadeTo(400, 0);
        $('.img2').stop().fadeTo(400, 1);
    } 
}

Here's a shorter way of writing it.

function mouseOverOut(t) {
    $('.img1').stop().fadeTo(400, t ? 1 : 0);
    $('.img2').stop().fadeTo(400, t ? 0 : 1);
}

Or this may work. Test it first, though.

function mouseOverOut(t) {
    $('.img1').stop().fadeTo(400, t);
    $('.img2').stop().fadeTo(400, !t);
}

EDIT: This last one seems to work. The true/false is translated to 1/0. You could also use .animate() directly.

function mouseOverOut(t) {
    $('.img1').stop().animate({opacity: t});
    $('.img2').stop().animate({opacity: !t});
}


Did you already try stop() ?

Description: Stop the currently-running animation on the matched elements.


using .stop()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜