我有一個元素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