本文介绍了如何检测鼠标何时停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经编写了以下JavaScript代码.我正在使用它来检测鼠标何时移动以及何时停止. MouseStopped()函数是一个包含数百个项目的循环,它将告诉我鼠标在哪里停止,所以我只想在鼠标停止时调用它.
I have written the following JavaScript code. I am using it to detect when the mouse is moving and when it has stopped. MouseStopped() function is a loop of hundreds of items that will tell me where the mouse has stopped, so I want to call it only when the mouse has stopped.
var CheckMovement;
var stopLoop = false;
var n = 0;
canvas.addEventListener('mousemove', function (evt) {
CheckMovement = setInterval(function () { HasMouseStopped(evt) }, 250);
}, false)
function HasMouseStopped(evt) {
var mousePos = getMousePos(canvas, evt);
newMouseX = mousePos.x;
newMouseY = mousePos.y;
if ((newMouseX !== mouseX) && (newMouseY !== mouseY)) {
stopLoop = true;
} else {
//stopped moving
clearInterval(CheckMovement);
stopLoop = false;
n = 0;
MouseStopped();
}
mouseX = newMouseX;
mouseY = mousePos.y;
}
function MouseStopped() {
while (arr.length > n) {
if (stopLoop) { break; }
if (ctx.isPointInPath(mouseX, mouseY)) {
//tooltip text
ctx.font = '12pt Candara';
ctx.fillStyle = 'black';
ctx.fillText(arr[n], mouseX + 10, mouseY - 5);
break;
}
n++;
}
}
现在我遇到以下问题:
- 即使我正在呼叫
clearInterval(CheckMovement)
,它也不会停止迭代;它持续运行,导致出现问题多次调用MouseStopped()
. 为什么不停止? - 如果要在完成循环之前移动鼠标,我想在操作的中间中断
MouseStopped()
.这就是为什么我要设置stopLoop = true;
的原因.但是,这似乎也没有按预期工作. 如何实现这些目标?
- Even though I am calling
clearInterval(CheckMovement)
, it doesn'tstop iterating; it is running continuously, which cause the problem ofcallingMouseStopped()
multiple times. Why is it not stopping? - I would like to break
MouseStopped()
in the middle of its operation if the mouse is moved before it completed its the loop. This is why I am settingstopLoop = true;
However, that also doesn't seem to be working as intended. How can I achieve these?
谢谢.
编辑
推荐答案
这非常简单:移动鼠标时,请将超时设置为XXX毫秒.另外,清除所有过去的超时以重置时间.在mousemove侦听器中是这样的
It's really simple: when the mouse is moved, set a timeout for XXX milliseconds in the future. Also, clear any past timeouts to reset the time. Like this in the mousemove listener
clearTimeout(timer);
timer=setTimeout(mouseStopped,300);
请参见 JSFiddle .
这篇关于如何检测鼠标何时停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!