简体   繁体   English

一定时间后开启/关闭功能

[英]On / Off function after a certain period of time

Wondering how you can make .off() only happen for a specific period of time. 想知道如何使.off()仅在特定时间段内发生。 I have a div which once clicked i want to disable the click event for 2 seconds, and then be allowed to click again. 我有一个div,一旦单击,我想禁用click事件2秒钟,然后允许再次单击。 At the moment all I have is the div can be clicked, then once clicked it is off. 目前我所能做的就是单击div,然后单击它就关闭了。

Here is a brief example of what I am asking: 这是我要问的简短示例:

$('.test').on('click', function() {
    // *do stuff*
    $('.test').off('click'); *for a certain perdiod of time*
});

It's a much simpler task to use a boolean variable as a flag to state whether the click handler should be executed, instead of attaching/detaching events from multiple elements. 使用布尔变量作为标志来声明是否应执行单击处理程序,而不是附加/分离多个元素中的事件,是一项非常简单的任务。 Try this: 尝试这个:

var clickEnabled = true;

$('div').click(function() {
    clickEnabled = false;
    setTimeout(function() {
        clickEnabled = true;
    }, 2000);
});

$('.test').on('click', function(e) {
    if (!clickEnabled) {
        e.preventDefault();
    } else {
        // do stuff...
    }
});

Note that you should also make the fact that .test is disabled visible in the UI, otherwise you'll just confuse and annoy your visitors when they click an element expecting an action, but nothing happens. 请注意,您还应该使禁用.test的事实在用户界面中可见,否则,当访问者单击需要执行操作的元素时,它们只会使访问者感到困惑和烦恼,但是什么也不会发生。

What about activate on after a certain period of time? 一段时间后激活怎么办?

function myFunction() {
   ...do stuff
   $('.test').off('click'); for a certain perdiod of time
   setTimeout(function(){ $('.test').on('click', myFunction)}, 2000);
}

Using the setTimeout you may do something like: 使用setTimeout,您可以执行以下操作:

var enabled = true;
var timeoutSeconds = 2;

$(function () {
  $('.test').on('click', function(e) {
    if (enabled) {
      // *do stuff*
      enabled = false;
      window.setTimeout(function() {
        enabled = true;
      }, timeoutSeconds * 1000);
    } else {
      e.preventDefault();
    }
  });
});

You could do it like this. 您可以这样做。

function onClick() {

  // do stuff here

  $('.test').off('click');

  setTimeout(function(){
       $('.test').on('click', onClick);
  }, 2000)
}

$('.test').on('click', onClick);

Or you can do it with css and toggleClass 或者您可以使用css和toggleClass做到这一点

// css
.disabled {
  pointer-events: none;
}

// js
$('.test').on('click', function(){
   // do stuff here

   $('.test').addClass('disabled');
   setTimeout(function(){
     $('.test').removeClass('disabled');
   }, 2000);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM