2013-06-05 284 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。 –