2011-12-01 46 views
0

我使用下面的代碼進行動畫影像懸停動畫調用多次

$('body').prepend('<div id="Checker"></div>'); 

$('#Checker').hover(
function() { $(this).animate({ height: '+=20' });}, 
function() { $(this).animate({ height: '-=20' });} 
); 

它工作正常,但是當我將鼠標懸停多次將不間斷動畫..
我想要調用懸停一個動畫完成後的動畫。

回答

5

你需要一些站:

$('body').prepend('<div id="Checker"></div>'); 

$('#Checker').hover(
function() { $(this).stop(true).animate({ height: '+=20' });}, 
function() { $(this).stop(true).animate({ height: '-=20' });} 
); 

jQuery stop();

或者,如果動畫正在運行檢查:

if($(elem).is(':animated')) { //do something } 

結合他們:

$('#Checker').hover(
    function() { 
    $(this).not(':animated').stop(true, true).animate({ height: '+=20' }); 
    }, 
    function() { 
     $(this).not(':animated').stop(true, true).animate({ height: '-=20' }); 
    } 
); 

但你仍然如果鼠標在動畫完成之前離開元素會出現問題,您的第二個最佳選擇是放棄不動畫的部分,然後停下來(true,true),最好的選擇是放棄+ =/- =,直接設置值,這樣你就知道他們會是什麼,並且可以在你的動畫上實現一些控制,並且標誌也可以正常工作。

+0

此代碼是完全吃在第二懸停DIV高度。這裏是小提琴http://jsfiddle.net/dUSHu/1/ – Exception

+1

因爲你加/減的高度,你需要檢查先前的動畫是否完成,或者你可以使用跳轉到結束選項設置停止(真,真);即使設置標誌在添加/減少時並不真正可靠,而不是實際設置值。 – adeneo

0

嘗試設置一些標誌指示動畫是否正在進行(PS:沒有測試):

var animating = false; 
$('#Checker').hover(
    function() { 
     if (animating === false) { 
      animating = true; 
      $(this).animate({ height: '+=20' }, function() {animating = false;}); 
     } 
    }, 
    function() { 
     if (animating === false) { 
      animating = true; 
      $(this).animate({ height: '-=20' }, function() {animating = false;});} 
     } 
);