2011-08-05 5 views
1

ボタンをクリックすると、divがアニメーション化されます。2回目のクリックで最初にアニメーションが完了するコールバック関数

$.animate() [complete]コールバック関数を使用しようとしていますが、ボタンを2回クリックすると、最初のアニメーションの[complete]コールバックが実行される前にアニメーションが2回実行されます。

デモ用のリンクをご覧ください。 http://jsfiddle.net/zs2uf/3/

2番目のクリックが最初のコールバックを倒すのを防ぐ方法を教えてください。

答えて

3

クリックした直後にボタンを無効にしてから、アニメーションを実行する必要があります。

ボタンを1回だけクリックできるようにしますが、ボタンを無効にする前にアニメーションが完了するまで待つようにしたいとします。これは、アニメーション中にボタンが再度クリックされる可能性があるので、プログラムが望むように動作しない理由です。ここで

がどのようにボタンに確認することで、一度だけクリックすることができます。

$("#next").click(function(){ 

    var pos = parseInt($("#box").css("left")), 
     newPos = pos + 100; 

    // disable button immediately after the click 
    // if you wait to disable, you give the user the chance to click twice 
    $("#next").unbind('click'); 
    $("#next").attr("disabled", "disabled"); 

    $("#box").animate({ 
     "left" : newPos //move the box to the right by 100px 
    }, { 
     duration: 150 
    });   
}) 

Working example

unbind()は多くのブラウザでは必要ないかもしれないが、それは、クリックイベントハンドラであることを保証します実際には#nextから削除されました。

+1

感謝を見てみましょう修正しました。 – fortuneRice

1

はそれが私は、ユーザーがまだ進行中でアニメーションしながら、クリックできることを忘れてしまった@Peterこの

http://jsfiddle.net/zs2uf/5/

コード

$("#next").click(function(){ 


    var pos = parseInt($("#box").css("left")); 
    var newPos = pos + 100; 

    if($("#box:animated").length == 0){ 

     $("#box").animate({ 
      "left" : newPos //move the box to the right by 100px 
     }, { 
      duration: 150, 
      complete: function(){ 

      //after moving the box by 100px, disable the next button, 
      //so that the box can move no further than 100px 
      $("#next").attr("disabled", true); 

      } 
     }); 
    } 





    //problem: 
    //if you click the Next button twice really fast, 
    //the box moves twice before the button is disabled 

}) 
+0

ありがとうございます@ShankarSangoli私は:アニメーションセレクターの前に知りませんでした。 – fortuneRice

関連する問題