【问题标题】:jquery- avoid double clicksjquery-避免双击
【发布时间】:2012-04-07 05:48:37
【问题描述】:

我有一个简单的动画,问题是我希望动画在我再次点击之前结束?

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

 $('#result').animate({
    left: '-=250',
   }, 1000, function() {
  pos = $('#result').position();

  if (pos.left <= -550) {
$('.next').hide();
  }
  if (pos.left <= -250) {
    $('.prev').show();
  }
});

【问题讨论】:

  • 你有小提琴可以分享吗?

标签: jquery events click jquery-animate


【解决方案1】:

答案很简单,使用.data()方法在item上设置一个可点击标志。您可以在您的完整功能中重新启用它。

来自 jQuery.com:.data() Documentation

.data() 方法允许我们以一种安全的方式将任何类型的数据附加到 DOM 元素,从而避免循环引用,从而避免内存泄漏。

我们可以为单个元素设置多个不同的值并在以后检索它们:

在您的动画上使用 complete 方法(您已经使用该方法来显示/隐藏您的下一个/上一个按钮,我们可以重新启用该按钮以被点击。

请注意,我们将$(this) 存储到btn 中,因此可以从complete 函数的闭包中访问它。

$(".next").click(function() {
  var btn = $(this);
  if (btn.data('running'))
    return;

  btn.data('running', true);

  $('#result').animate({
    left: '-=250',
    }, 1000, function() {
       pos = $('#result').position();

       if (pos.left <= -550) {
         $('.next').hide();
       }
       if (pos.left <= -250) {
         $('.prev').show();
       }

       // Unset it here, this lets the button be clickable again
       btn.data('running', false);
    }
   );
});

【讨论】:

  • .datadata-item="asd" 属性不同。它从 jQuery 1.3 开始就存在,并存储引用到包装该 dom 的 jQuery 对象的数据。从 jQuery 1.4.3 开始,.data() 由 data-attributes 自动填充,但在 HTML5 之前完全支持 .data()。它实际上只是在内存中存储一​​个 javascript 对象。
【解决方案2】:

你可以让动画在animate再次开始之前自动结束:

$('#result').stop(true, true).animate({ ...

【讨论】:

    【解决方案3】:

    禁用单击按钮并使用 .animate 函数的完整函数调用重新启用它:

    .animate( properties [, duration] [, easing] [, complete] )

    完成动画完成后调用的函数。

    【讨论】:

      【解决方案4】:

      在点击时禁用按钮,并在相同的时间后使用“SetTimeout”功能启用它。

      $(".next").click(function() {
      
         $(this).enabled = false;
         setTimeout('enableButtons()', 250);     }
      
         $('#result').animate({
            left: '-=250',
         }, 1000, function() {
          pos = $('#result').position();
      
        if (pos.left <= -550) {
      $('.next').hide();
        }
        if (pos.left <= -250) {
          $('.prev').show();
        }
      });
      
      function enableButtons() {
          $(".next").enabled = true;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-05
        • 2016-04-02
        • 2012-10-17
        • 1970-01-01
        • 1970-01-01
        • 2014-08-04
        相关资源
        最近更新 更多