Javascript 2个事件侦听器,运行函数一次

Javascript 2个事件侦听器,运行函数一次,javascript,Javascript,我有两个事件监听器,一个用于点击和触摸事件。它们都应该运行相同的函数,但只能运行一次。如果在某些设备上两者都为真,则会运行该函数两次 我希望能够单击一个按钮并侦听两个事件侦听器,但如果其中任何一个被触发,则只运行该函数一次 window.addEventListener("click", function(event) { myFunction(); }); window.addEventListener("touchstart", function(event) { myFun

我有两个事件监听器,一个用于点击和触摸事件。它们都应该运行相同的函数,但只能运行一次。如果在某些设备上两者都为真,则会运行该函数两次

我希望能够单击一个按钮并侦听两个事件侦听器,但如果其中任何一个被触发,则只运行该函数一次

window.addEventListener("click", function(event) {
    myFunction();
});
window.addEventListener("touchstart", function(event) {
    myFunction();
});

function myFunction() {
    console.log("Clicked");
}
见:

如果浏览器因单个事件同时触发触摸和鼠标事件 用户输入时,浏览器必须在启动任何鼠标之前启动touchstart 事件。因此,如果应用程序不需要鼠标事件 在特定的触摸目标元素上触发,该元素的触摸事件 处理程序应该调用preventDefault(),并且不需要额外的鼠标事件 将被派遣

下面是touchmove事件处理程序调用 preventDefault()

见:

如果浏览器因单个事件同时触发触摸和鼠标事件 用户输入时,浏览器必须在启动任何鼠标之前启动touchstart 事件。因此,如果应用程序不需要鼠标事件 在特定的触摸目标元素上触发,该元素的触摸事件 处理程序应该调用preventDefault(),并且不需要额外的鼠标事件 将被派遣

下面是touchmove事件处理程序调用 preventDefault()


假设两个事件几乎同时触发,可以使用以下方法防止
myFunction
在预定义阈值内执行两次:

// threshold to reset allowing the execution
const _msThreshold = 200;

// date at which the function is last executed
let _myFnExecutedAt = new Date(0);

// your function
function myFunction() {
    console.log("Clicked");
}

// executer that checks if the threshold is exceeded
// to allow your function call and reset the timer
function execute() {
    if (new Date() - _myFnExecutedAt > _msThreshold) {
        myFunction();
        _myFnExecutedAt = new Date();
    }
}

window.addEventListener("click", execute);
window.addEventListener("touchstart", execute);
请记住,您必须对阈值进行一些试验:

  • 如果将其设置得太低,则可能会在第二个事件寄存器之前超过该值,因此这两个事件都将触发
  • 如果设置得太高,后续的实际点击/触摸可能无法注册

假设两个事件几乎同时触发,可以使用以下方法防止
myFunction
在预定义阈值内执行两次:

// threshold to reset allowing the execution
const _msThreshold = 200;

// date at which the function is last executed
let _myFnExecutedAt = new Date(0);

// your function
function myFunction() {
    console.log("Clicked");
}

// executer that checks if the threshold is exceeded
// to allow your function call and reset the timer
function execute() {
    if (new Date() - _myFnExecutedAt > _msThreshold) {
        myFunction();
        _myFnExecutedAt = new Date();
    }
}

window.addEventListener("click", execute);
window.addEventListener("touchstart", execute);
请记住,您必须对阈值进行一些试验:

  • 如果将其设置得太低,则可能会在第二个事件寄存器之前超过该值,因此这两个事件都将触发
  • 如果设置得太高,后续的实际点击/触摸可能无法注册

touchstart
单击不同@Rajesh是的,我需要两者都监听,但有时它们会重叠,在某些设备上都会触发。如果发生这种情况,我需要加入他们,这样他们只运行一次函数。您可以使用一个全局变量来保持函数的启动状态。我的意思是,
touchstart
mousedown
相同。A
单击
组合/sums
mousedown
mousepress
mouseup
。因此,您有两个生命周期事件,因此它将被调用两次
touchstart
click
@Rajesh是的,我需要两个事件都侦听,但有时它们会重叠,在某些设备上都会触发。如果发生这种情况,我需要加入他们,这样他们只运行一次函数。您可以使用一个全局变量来保持函数的启动状态。我的意思是,
touchstart
mousedown
相同。A
单击
组合/sums
mousedown
mousepress
mouseup
。因此,您有2个生命周期事件,因此它将被调用两次