【问题标题】:Trying to stop jQuery click event as long as animation works只要动画有效,就试图停止jQuery点击事件
【发布时间】:2011-01-30 21:42:48
【问题描述】:

我有一个内容滑块,另外我制作了“上一个”和“下一个”按钮。只有在动画完成时(动画持续时间为 500 毫秒),按钮才能被点击。我试图用 :animated 选择器解决它,但它不起作用:

if (!$(".scrollContainer").is(':animated')) {
    $(".nextItems a").click(function() {
        $(".slideNavig").find('a.selected').removeClass('selected').parent().next().find("a").addClass('selected');
    });
}
if (!$(".scrollContainer").is(':animated')) {
    $(".prevItems a").click(function() {
        $(".slideNavig").find('a.selected').removeClass('selected').parent().prev().find("a").addClass('selected');
    });
}

或者很简单,我需要在单击后停止按钮单击事件 500 毫秒。谁能帮帮我?

【问题讨论】:

  • 利用.unbind()方法api.jquery.com/unbind
  • @aSeptik 绑定然后解除绑定然后重新绑定是不好的。最好使用标志或检查来决定是否应该处理事件而不是进行(取消)绑定舞蹈。
  • @PetersenDidIt - 是的,你是对的!

标签: javascript jquery timeout conditional-statements


【解决方案1】:

移动 if 语句来检查你的 click 事件处理程序中是否有动画:

$(".nextItems a").click(function() {
    if (!$(".scrollContainer").is(':animated')) {
        $(".slideNavig").find('a.selected').removeClass('selected').parent().next().find("a").addClass('selected');
    }
});

$(".prevItems a").click(function() {
    if (!$(".scrollContainer").is(':animated')) {
        $(".slideNavig").find('a.selected').removeClass('selected').parent().prev().find("a").addClass('selected');
    }
});

您还可以通过执行以下操作来干掉您的代码:

$(".nextItems a").click(function() {
    nextPrevItem('next');
});

$(".prevItems a").click(function() {
    nextPrevItem('prev');
});
function nextPrevItem( direction ) {
    if (!$(".scrollContainer").is(':animated')) {
        $(".slideNavig").find('a.selected').removeClass('selected')
            .parent()[ direction ]()
            .find("a").addClass('selected');
    }   
}

【讨论】:

  • 是的,你是对的! if 语句必须在事件内部。但是您的第二个解决方案胜过一切!伟大的!这就是你这样做的原因!非常感谢!
【解决方案2】:

您需要在处理程序中使用 if 语句:

$(".nextItems a").click(function() {
    if (!$(".scrollContainer").is(':animated')) {
        $(".slideNavig").find('a.selected').removeClass('selected').parent().next().find("a").addClass('selected');
    }
});

$(".prevItems a").click(function() {
    if (!$(".scrollContainer").is(':animated')) {
        $(".slideNavig").find('a.selected').removeClass('selected').parent().prev().find("a").addClass('selected');
    }
});

【讨论】:

    【解决方案3】:

    您可以使用.delay()(在 jQuery 1.4 及更高版本中可用)或者您可以使用.setTimeOut()

    http://forum.jquery.com/topic/settimeout-15-6-2010

    http://api.jquery.com/delay/

    【讨论】:

      猜你喜欢
      • 2010-12-16
      • 1970-01-01
      • 2014-01-07
      • 2011-01-29
      • 2017-01-19
      • 2013-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多