这是我的代码:
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)
}
}
当我按下时,
increaseRad
会运行,但里面的while循环永远不会结束。
知道为什么吗?
这里的问题是您的代码作为阻塞循环运行。
while(mouseDown){
console.log("mouse is still down");
rad++;
console.log(rad)
}
浏览器在单个线程中计算 Javascript,并且该循环永远不会暂停以让浏览器处理这些事件处理程序。
相反,您可以仅使用异步函数来侦听 mousedown 事件,然后启动计时器。如果计时器结束时鼠标仍然按下,那么您可以将其算作长按。
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;
});
这些异步操作(
addEventListener
、setTimeout
)不会阻塞主线程。
如果连续单击多次,则会出现错误的单击并按住。更好的解决方案是...
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;
});
var timer;
document.addEventListener('mousedown', function() {
timer = setTimeout(function() {
// press and hold logic
console.log('Press and hold event detected (non-touch)');
}, 500);
});
document.addEventListener('mouseup', function() {
clearTimeout(timer);
});
很抱歉在这里发表评论,但我也遇到了困难。 我不想提出新问题,因为我的代码是相同的,但我的问题与长时间单击并移动鼠标然后停止移动后有关,但保持单击,计时器中的代码为
mousedown
不再被称为:
let isMouseDown = false;
let intervalId = null;
canvas.addEventListener('mousedown', (event) => {
if (!isMouseDown) {
isMouseDown = true;
handleMouseClick(event);
intervalId = setInterval(() => {
handleMouseClick(event);
}, 30);
}
});
canvas.addEventListener('mouseup', () => {
isMouseDown = false;
clearInterval(intervalId);
});
canvas.addEventListener('mousemove', (event) => {
if (isMouseDown) {
handleMouseClick(event);
clearInterval(intervalId);
}
});
那么有人可以帮助我解决这种情况,重申,单击并按住,移动鼠标,停止移动鼠标,
mousedown
调用停止。