2011-06-09 132 views
1

下面我有一些代碼基本上動畫從頁面底部的div到頂部。當我將鼠標懸停在div上時,我希望動畫立即停止,併爲div賦予不透明度值0.25。當鼠標離開div時,我想要動畫繼續停用動畫時懸停

現在動畫不停止,不透明度值在動畫完成後給出,而不是立即生效。

那麼如何獲得我想要的結果?

<!DOCTYPE html> 
<html> 
<head> 
<style> 
#bubble{ 
border-radius:20px; 
margin:3px; 
width:40px; 
height:40px; 
position:absolute; 
left:0px; 
top:1000px; 
background:green; 
display:none; 
} 
</style> 
<script src="http://code.jquery.com/jquery-latest.js"></script> 
</head> 
<body> 
<div id="bubble"></div> 
<script> 
function runIt() { 
$('#bubble').show(0); 
$('#bubble').animate({top:'-=1000px',},5000); 
$('#bubble').animate({top:'+=1000px',},0); 
$('#bubble').hide("normal", runIt); 
} 

runIt(); 

$('#bubble').hover(function() { 
    $('#bubble').animate({ 
    opacity: 0.25, 
    }, 500, function() {}); 
}); 
</script> 
</body> 
</html> 

回答

0

在懸停事件中,您需要調用。 stop(true,false)。然後在退出功能(當前爲空)中,您需要從當前位置重新開始動畫。

<script> 
function runIt() { 
$('#bubble').show(0); 
$('#bubble').animate({top:'-=1000px'},5000); 
$('#bubble').animate({top:'+=1000px'},0); 
$('#bubble').hide("normal", runIt); 
} 

runIt(); 

$('#bubble').hover(function() { 
    $(this).stop(true, false); 
    $(this).animate({ 
    opacity: 0.25, 
    }, 500); 
}, function() { 
    runIt(); 
    }); 
</script> 
0

您正在尋找.stop()。您可以使用它來停止mouseover上選定元素上運行的任何動畫(並可選擇使其立即轉到動畫的邏輯結尾),並重新啓動hover()mouseout組件上的動畫。

$('#bubble').animate({ 
    // blah 
}).hover(function() { 
    // stop animation 
    $(this).stop().css({ opacity : 0.25 }); 
}, function() { 
    // continue animation 
    $(this).css({ opacity : 1.0 }).animate({ /* blah */ }); 
}); 

然而,看着你的代碼,您使用的增量動畫(使用即+=1000px的東西,而不是像固定1000px)。因此,您必須以某種方式跟蹤動畫的進度,並在mouseout上應用經過調整的增量。

例如,如果#bubble的動畫,然後你就可以懸停,你應該能夠確定它已經移動300px例如,並且呼籲繼續調整的.animate({ top : '-=700px' })

如果您爲動畫使用固定值,在繼續調用原始動畫時不應該出現問題。