I am using the jQuery hover event to cause an element to "glow" (opacity change from 0.7 to 1) and then "unglow" when the mouse leaves. This is great except when you accidentally run the mouse over the element a few to many times. The element will then start flashing ("glowing" and "unglowing") as many times as the mouse went through it.
Not only is this ugly but it also means that any other jQuery .animate() event that needs to be run has to wait until these successive flashes have finished. An example can be found here: http://www.rootsoftllc.com/accounts/
Is there a way to tell the jQuery hover event that it can only run once and then it has to wait until it's completed before it 开发者_JAVA技巧can except any more mouse events?
Yes, it's actually quite simple. Before initiating the animation with .animate()
put .stop()
in there to stop any other animations in the queue.
Read up on it here:
The jquery online documentation on .stop()
You can use .stop(true, true)
to stop and clear the animation queue, like this:
$('.window').hover(function() {
$(this).stop(true, true).animate({opacity: 1}, 500);
}, function() {
$(this).stop(true, true).animate({opacity: 0.7}, 500);
});
In jQuery, you can give every animation it's own queue. I suggest you give the hover effect a queue of its own so that it doesn't interfere with other animations. Then, you could check how long the mouse was inside the element. If it hasn't been there long enough for the animation to finish, use .stop() to stop the animation prematurely, and make a quick animation back to where it's supposed to be.
精彩评论