2013-04-29 83 views
0

我有一个元素bottom: 10。我想让它在盘旋时变成20。回来到10鼠标了:元素不能恢复到原来的位置?

$('.home-box-caption a').hover(function() { 
    $('.home-box-caption a').animate({ 
    bottom: 20 
    }, 200, function() { 
    bottom: 10 
    }); 
}); 

现在它只是停留在20

我做错了什么?

回答

1

您没有正确使用.hover()

.hover(function[, function])

var $targets = $('.home-box-caption').find('a'); 
$targets.hover(function() { 
    $(this).animate({ 
    bottom: 20 
    }, 200); 
}, function(){ 
    $(this).animate({ 
    bottom: 10 
    }, 200); 
}); 

考虑使用this关键字(除非你的意图是动画.home-box-caption下的所有a元素),或存放在变量这些元素,这样你就不必每次重新查询DOM 。

了解更多:http://api.jquery.com/hover/

+0

哦,是的,我只是想要动画当前元素 – alexchenco 2013-04-29 08:20:50

+0

@alexchenco - 我已经更新了我的答案,以反映只针对当前元素,使用'$(this) – ahren 2013-04-29 08:21:39

0

你可能会喜欢使用悬停的第二个参数是这样

 $('.home-box-caption a').hover(function() { 
      $(this).animate({ 
       bottom: 20 
      }, 200) 
     }, function() { 
      $(this).animate({ 
       bottom: 10 
      }, 200) 
     }); 
0

的元素动画回鼠标移开时,你应该把第二动画为hover第二个参数:

$('.home-box-caption a').hover(
    function(){ 
    //this is invoked when the mouse ENTERS the element 
    $(this).animate({top: 140}, 200); 
    }, 
    function(){ 
    //this is invoked when the mouse LEAVES the element 
    $(this).animate({top: 150}, 200); 
    } 
); 

http://jsfiddle.net/fnpuC/

hover方法支持回调:.hover(handlerIn(eventObject), handlerOut(eventObject))。请参阅http://api.jquery.com/hover/

第一个将在鼠标进入元素时调用,第二个在元素离开时调用。

animate方法也支持回调:.animate(properties [, duration ] [, easing ] [, complete ]),但是当第一个动画完成时,将调用此回调。

相关问题