2009-07-03 52 views
3

我已經使用jQuery進行小型動畫工作:表#photos包含9張照片,我希望在mouseover上使用animate函數來增加寬度和高度。但是,當用戶將鼠標移動到另一張照片時,動畫正在運行,它會自動觸發下一個動畫,因此它完全混亂。我該怎麼辦?我的代碼是:如何讓一個函數等到動畫完成?

$(function(){ 
    $("#photos tr td img").mouseover(function(){ 
    $(this).animate({"width":"1000px","height":"512px"},2000) 
    }); 
    $("#photos tr td img").mouseout(function(){ 
    $(this).animate({"width":"100px","height":"50px"},2000) 
    });  
}); 
+1

只是一個提示:使用懸停功能,而不是鼠標懸停及移出。 http://docs.jquery.com/Events/hover – 2009-07-03 12:11:29

回答

6

jQuery提供回調動畫完成時。 然後,它可能是這樣的,例如:

var animating = false; 
$(function(){ $("#photos tr td img").mouseover(
    function() 
    { 
     if(!animating) 
      $(this).animate({"width":"1000px","height":"512px"},2000, easing, function() { animating = true; }); 
    }); 

    $("#photos tr td img").mouseout(
     function() 
     { 
      $(this).animate({"width":"100px","height":"50px"},2000, easing, function() { animating = false; }) 
     }); 
}); 
4

你應該開始一個新的,以避免陷入困境之前,停止所有正在運行的動畫。 這可能是針對這個特定問題的最好和直接的解決方案。

$(function(){ 
    $("#photos tr td img").mouseover(function(){ 
    $(this).stop(); 
    $(this).animate({"width":"1000px","height":"512px"},2000) 
    }); 
    $("#photos tr td img").mouseout(function(){ 
    $(this).animate({"width":"100px","height":"50px"},2000) 
    });  
}); 
+1

除了你也可以鏈EM。 $(this).stop()。animate(...)並使用「hover」 – mpen 2009-07-03 20:41:43

1

除了其他答案我會考慮使用hoverIntent插件。這只是避免在用戶將鼠標移動到所有照片上時設置大量的動畫隊列。如果用戶實際上被徘徊,你只需要動畫。

1

我想答案取決於你想在第二次發生什麼事情(而第一次仍然是動畫)。

1)如果你想什麼事情發生,你可以有你的第一個懸停設置「動畫效果」的狀態,對整個TR,也許是這樣的:

$tr = $(this).closest("tr"); 
    if ($tr.data("animating") != true) { 
     $tr.data("animating",true); 
     $(this) 
     .stop(true,false) 
     .animate({"width":"1000px","height":"512px"},2000, function(){ 
      $tr.data("animating",false); 
     }); 
    } 

2)如果你想在原來的動畫結束所以你的新圖像可以生成動畫,你需要使用.stop()將clearQueue和goToEnd參數設置爲true。這將確保額外的排隊事件(從一大堆懸停的)不只是不停發生幾分鐘,它會做動畫,立即跳到最終狀態:

$(this).closest("tr").find("img:animated").stop(true,true); 
    $(this).animate({"width":"1000px","height":"512px"},2000}); 
0

一定要檢查的隊列動畫元素,永遠不會從現在得到的衝突:

$(function(){ 
    $("#photos tr td img").mouseover(function(){ 
    if($(this).queue("fx").length == 0) 
     $(this).animate({"width":"1000px","height":"512px"},2000) 
    }); 
    $("#photos tr td img").mouseout(function(){ 
     $(this).animate({"width":"100px","height":"50px"},2000) 
    });  
});