鼠标悬停时的Jquery动画

18

我有一段文字,希望在鼠标悬停时进行动画效果,例如:

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

使用这个代码时,当我将鼠标悬停在行上时,表格列会通过微小移动进行动画处理。

问题在于:当我反复移动鼠标光标并停止后,即使我不在其上移动鼠标,动画仍会继续一段时间。稍后它仍然会自己保持运动。

如何停止它?

4个回答

36
我在stackoverflow上找到了一篇非常好的关于jquery悬停平滑动画的文章,作者是Chris Coyier,文章发布在CSS Tricks上。所以将此应用于你的代码看起来像这样:

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

$(".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');
});

本质上,它会检查该行是否正在进行动画,如果没有,则只会调用mouseenter动画。

希望您的行现在能够像此页面上的最后两个示例一样进行动画:

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


3

我按照自己的想法做了一些更改,具体如下:"animate({marginLeft:'0px'},0)"

请查看以下代码:

$(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) });
});

1

jQuery为您的需求提供了特殊的事件处理程序 :) 使用mouseentermouseleave

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

1

听起来你想绑定到mousemove而不是hover,但也要创建一个mouseout处理程序,例如$(foo).mouseout(function(){$(this).stop();})来终止动画。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接