jQuery 鼠标悬停和移出事件

27

我想在鼠标悬停链接时出现简单的向下/向上滑动动画。我能够实现鼠标悬停效果,但我无法解决鼠标移出时的问题。

以下是我的悬停效果代码:

<script type="text/javascript" src="http://www.google.com/jsapi"></script>

<script type="text/javascript">

google.load("jquery", "1.3.2"); //load version 1.3.2 of jQuery

google.setOnLoadCallback(function() {
    jQuery(
        function($) {
            $("a.button").hover(function(){$(this).animate({"marginTop": "0px"}, "fast")   

        });
    });
});
</script>

当鼠标移出时,如何将这个边距向上移动16px?


示例代码不正确!也许你缺少了 .hover(func,func) 的第二个函数? - Boldewyn
3个回答

81

在jQuery中,hover事件需要两个回调函数:一个是当指针移动到元素上时触发的,另一个是当指针离开元素时触发的:

$(item).hover(function() { ... }, function() { ... });
在您的情况下:
$("a.button").hover(
   function() {
      $(this).animate({"marginTop": "0px"}, "fast");
   },
   function() {
      $(this).animate({"marginTop": "16px"}, "fast");
   }
);

21

在 jQuery 的新版本(>=1.7)中,您也可以采用以下方法:

$("a.button").on('mouseenter',function(){
  $(this).animate({"marginTop": "0px"}, "fast");
});
$("a.button").on('mouseleave',function(){
  $(this).animate({"marginTop": "16px"}, "fast");
});

在我看来,这是一种更简洁的方法,并且还利用了新的 .on() 函数(文档在这里)。


1

更简单的解决方案:

$("a.button").hover(function() {
  $("a.button").css("cursor","pointer");
});

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