我有一个元素bottom: 10
。我想让它在盘旋时变成20。回来到10鼠标了:元素不能恢复到原来的位置?
$('.home-box-caption a').hover(function() {
$('.home-box-caption a').animate({
bottom: 20
}, 200, function() {
bottom: 10
});
});
现在它只是停留在20
我做错了什么?
我有一个元素bottom: 10
。我想让它在盘旋时变成20。回来到10鼠标了:元素不能恢复到原来的位置?
$('.home-box-caption a').hover(function() {
$('.home-box-caption a').animate({
bottom: 20
}, 200, function() {
bottom: 10
});
});
现在它只是停留在20
我做错了什么?
您没有正确使用.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 。
你可能会喜欢使用悬停的第二个参数是这样
$('.home-box-caption a').hover(function() {
$(this).animate({
bottom: 20
}, 200)
}, function() {
$(this).animate({
bottom: 10
}, 200)
});
的元素动画回鼠标移开时,你应该把第二动画为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);
}
);
hover
方法支持回调:.hover(handlerIn(eventObject), handlerOut(eventObject))
。请参阅http://api.jquery.com/hover/
第一个将在鼠标进入元素时调用,第二个在元素离开时调用。
animate
方法也支持回调:.animate(properties [, duration ] [, easing ] [, complete ])
,但是当第一个动画完成时,将调用此回调。
哦,是的,我只是想要动画当前元素 – alexchenco 2013-04-29 08:20:50
@alexchenco - 我已经更新了我的答案,以反映只针对当前元素,使用'$(this) – ahren 2013-04-29 08:21:39