2013-06-05 281 views
2

我剛開始使用jQuery和一般的web開發,所以請原諒任何天真的錯誤。我試圖讓按鈕導致動畫發生。也就是說,這個動畫只是簡單地將'h2'標題從左向右移動,然後再移回(並且平均改變顏色)。防止onClick事件發生多次(jQuery)

我使用下面的代碼的問題是,如果用戶多次點擊按鈕,它會導致按鈕繼續超過轉折點。我瞭解到這是一個異步問題,並嘗試在動畫調用中使用回調函數來重新啓用按鈕功能。

正如你所看到的,我通過設置queue:false變量來解決這個問題。由於我還是這個新手,有沒有一種簡單的方法來做到這一點?

感謝您的幫助!

var toTheRight = true; 
$('#animation').click(function() { 
    var header = $('h2')[0].style.left.toString(); 
    var headerNum; 
    if (header.length < 5) { 
     headerNum = 0; 
    } 
    else { 
     headerNum = +(header.substring(0, header.length - 2)); 
    } 
    if (headerNum >= 450) { 
     toTheRight = false; 
     $('h2').css("background-color", "green"); 
    } 
    if (headerNum < 100) { 
     toTheRight = true; 
     $('h2').css("background-color", "orange"); 
    } 
    var modified; 
    var stringified; 
    if (toTheRight) { 
     modified = Math.round((headerNum + 100)/100) * 100; 
     strigified = modified + "px"; 
     $('h2').animate({ 
      "font-size": "3em", 
      "width": "50%", 
      "left": stringified 
     }, { queue: false, duration: 1000 }); 
    } 
    else { 
     modified = Math.round((headerNum - 100)/100) * 100; 
     stringified = modified + "px"; 
     $('h2').animate({ 
      "font-size": "3em", 
      "width": "50%", 
      "left": stringified 
     }, { queue: false, duration: 1000 }); 
    } 
}); 
+0

正是如此我明白,你希望用戶只能觸發一次事件,無論點擊多少次 按鈕? – gtr1971

+0

用戶可以根據需要多次觸發事件。因此,快速點擊按鈕是可以的,但我不希望動畫在沒有完成第一個調用的情況下發生25次。 –

回答

5

你可以用你的,如果這樣的功能:

$('#animation').click(function() { 
    if(!$('h2').is(':animated')){ 
     //your function 
    } 
}) 

編輯:

正如烤說,你可以這樣做:

$('#animation').click(function() { 
    if($('h2').is(':animated')) return; 
    //your function 
}) 
+2

哦,是的,忘記這一點! :)但似乎更好只是在頂部的功能:if($('h2')is(':animated'))return; –

+0

那麼這只是一個人的偏好,沒有perfomance獲得任何方式。但我同意它會起作用。 –

+0

應該是(!$('h2')。是(':animated')){}?我得到一個語法標記w/o。 –