简体   繁体   中英

How to do relative animating with Jquery on mouseover and mouseout?

I'm trying to have the following:

There is a fixed positioned div on the bottom of my page. When the mouse enters and exits the div animates its height to resp. 100px and 50px. The default height is 50px.

I've found that Jquery does this correctly with only one big no-no. When the mouse exits while animating and then reenters again it either:

a) stacks the animations leading to a lot (say 100) animations being done, while only one was necessary.

b) resets current animations, which leads to unexpected behavior like the div disappearing, changing to a fixed height which locks down or glitching up and down between 100 and 50 pixels.

Any ideas on this?

When you handle your mouseover and mouseout events, you should use the stop() function to clear the animation queue. It will let you jump to the end of the animation (before you start another one) if needed. You can also clear the whole queue of animations.

From the jQuery API documentation :

The usefulness of the .stop() method is evident when we need to animate an element on mouseenter and mouseleave:

<div id="hoverme">
  Hover me
  <img id="hoverme" src="book.png" alt="" width="100" height="123" />
</div>

We can create a nice fade effect without the common problem of multiple queued animations by adding .stop(true, true) to the chain:

$('#hoverme-stop-2').hover(function() {
  $(this).find('img').stop(true, true).fadeOut();
}, function() {
  $(this).find('img').stop(true, true).fadeIn();
});

Rather than firing off an animation event on every action, how about having a function that constantly polls specific variables, and acts accordingly - by moving or not moving a certain (variable) amount. Your mouseover and mouseout events would then modify those variables that are polled, and so you wouldn't have to worry about triggering hundreds of animations. Let me know if I'm not making sense so I can clarify..

The only solution I've found so far to work is to give both the mouseenter and mouseexit animation a ClearQueue() before animating, but I think this might be unwanted in some cases.

In the case of using animate() this works quite nicely, but with slideUp and other default JQuery animations it leads to improper behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM