无法在第一次单击时禁用链接,并在动画完成后重新启用

Unable to disable link on first click and re-enable when animation completes

本文关键字:新启用 启用 动画 单击 第一次 链接      更新时间:2023-09-26

我试图在点击链接时执行一个简单的动画。我希望链接应该在第一次点击后被禁用,只有在第一次调用后开始的动画完成后才能重新启用。

HTML:

<a id="link" href="#">Click</a>    
<div id="test" style="float:left;border:1px solid #000;width:100px;height:100px;">Test</div>
<div id="test2"></div>
​

jQuery:

$('#link').click(function(e){
  $('#link').bind('click', disableLink);
  ht = $('#test').height();
  $('#test').animate({height:'+=50'},5000,function(){$('#link').unbind('click', disableLink);});
  $('#test2').html(ht);
});
function disableLink(e) {
    e.preventDefault();
    return false;
}

Fiddle:http://jsfiddle.net/uHR7a/2/

您可以使用匿名函数来声明变量in_process,并取决于它是否启动新动画。

演示:http://jsfiddle.net/dUarG/1/

(function () {
    var in_process = false;
    $('#link').click(function (e) {
        e.preventDefault();
        if (!in_process) {
            in_process = true;
            $('#test').animate({height: '+=50'}, 2000, function () {
                in_process = false;
            });
        }  
    });
})();
​

在jquery:时使用此代码

   $('#link').click(function(e){
      $('#link').removeAttr('href');
      ht = $('#test').height();
      $('#test').animate({height:'+=50'},5000,function(){$('#link').attr('href', '#')});
      $('#test2').html(ht);
    });
    function disableLink(e) {
        e.preventDefault();
        return false;
    }

您可以使用on()off()进行以下操作:

$('#link').on('click', anim); //bind click
function anim(e) {
    $(e.target).off('click'); //unbind click when animating
    ht = $('#test').height();
    $('#test').animate({
        height: '+=50'
    }, 5000, function() {
        $(e.target).on('click', anim); //rebind when done
    });
    $('#test2').html(ht);
}​

FIDDLE