简体   繁体   English

在 Javascript 中检测按住鼠标单击

[英]Detect Hold Mouse-Click in Javascript

Here is my code:这是我的代码:

var mouseDown = false;

document.body.onmousedown = function() { 
  console.log("MOUSE DOWN");
  mouseDown = true;
  increaseRad();
}
document.body.onmouseup = function() {
  console.log("MOUSE UP");
  mouseDown = false;
}

function increaseRad(){
  rad = 0;
  while(mouseDown){
    console.log("mouse is still down");
    rad++;
    console.log(rad)
  }
}

When I press down, increaseRad is run, but the while loop inside never ends.当我按下时, increaseRad运行,但里面的 while 循环永远不会结束。

Any idea why?知道为什么吗?

The problem here is that your code runs as a blocking loop.这里的问题是您的代码作为阻塞循环运行。

while(mouseDown){
  console.log("mouse is still down");
  rad++;
  console.log(rad)
}

The browser evaluates Javascript in a single thread and this loop will never pause to let the browser process those event handlers.浏览器在单个线程中评估 Javascript,并且此循环永远不会暂停以让浏览器处理这些事件处理程序。

Instead you can use just use asynchronous functions to listen for mousedown events, then start a timer.相反,您可以仅使用异步函数来侦听 mousedown 事件,然后启动计时器。 If the mouse is still down when the timer finishes, then you can count it as a long click.如果计时器结束时鼠标仍然按下,那么您可以将其计为长按。

var mouseIsDown = false;

window.addEventListener('mousedown', function() {
  mouseIsDown = true;
  setTimeout(function() {
    if(mouseIsDown) {
      // mouse was held down for > 2 seconds
    }
  }, 2000);
});

window.addEventListener('mouseup', function() {
  mouseIsDown = false;
});

These asynchronous actions ( addEventListener , setTimeout ) won't block the main thread.这些异步操作( addEventListenersetTimeout )不会阻塞主线程。

If you click serveral times in a row, you get a wrong click & hold.如果您连续多次单击,就会出现错误的单击和按住。 Better solution is...更好的解决办法是...

var mouseIsDown = false;
var idTimeout;

window.addEventListener('mousedown', function() {
  mouseIsDown = true;
  idTimeout = setTimeout(function() {
    if(mouseIsDown) {
      // mouse was held down for > 2 seconds
    }
  }, 2000);
});

window.addEventListener('mouseup', function() {
  clearTimeout(idTimeout);
  mouseIsDown = false;
});

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

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