Jquery Animate on Hover

2019-02-08 02:10发布

问题:

I have a text which I want to animate when am having a mouse over it for eg:

$(".tabb tr").hover(
  function(){
    $(this).find("td #headie").animate({marginLeft:'9px'},'slow')
  },
  function() {
    $(this).find("td #headie").animate({marginLeft:'0px'},'slow')
  });

with this.. when am having mouse over the row.. the table column animates by moving little.

Problem here is: when I move the mouse cursor repeatedly over these rows and then stop and see.. the animation keeps going on for a while even if am not moving the mouse over it. IT KEEPS MOVING ITSELF later..

how can I stop that?

回答1:

A very well written article on smooth jquery animations on hover, that I found, was this one by Chris Coyier on CSS Tricks:

http://css-tricks.com/full-jquery-animations/

So fitting this to your code would look like this:

$(".tabb tr").hover(
function(){
  $(this).filter(':not(:animated)').animate({
     marginLeft:'9px'
  },'slow');
// This only fires if the row is not undergoing an animation when you mouseover it
},
function() {
  $(this).animate({
     marginLeft:'0px'
  },'slow');
});

Essentially it checks to see if the row is being animated and if it isn't, only then does it call the mouseenter animation.

Hopefully your rows will now animate somewhat like the last two examples on this page:

http://css-tricks.com/examples/jQueryStop/



回答2:

I got it the way I wanted.. the following was the change I made "animate({marginLeft:'0px'},0)"

Check the code below..

$(document).ready(function(){
    $(".tabb tr").mouseover(function(){ $(this).find("td #headie").animate({marginLeft:'9px'},'fast') });
    $(".tabb tr").mouseout(function(){ $(this).find("td #headie").animate({marginLeft:'0px'},0) });
});


回答3:

Sounds like you want to bind to mousemove not hover, but also create a handler for mouseout like $(foo).mouseout(function(){$(this).stop();}) to terminate the animations.



回答4:

jQuery provides special eventHandlers for your needs :) use mouseenter and mouseleave

$(".tabb tr").mouseenter(
  function(){
    $(this).find("td #headie").animate({marginLeft:'9px'},'slow')
  });
$(".tabb tr").mouseleave(
  function() {
    $(this).find("td #headie").animate({marginLeft:'0px'},'slow')
  });