简体   繁体   English

鼠标按下时的 JavaScript

[英]JavaScript while mousedown

var mdflag;
var count = 0;

document.addEventListener("mousedown",mdown,false);
    document.addEventListener("mouseup",mup,false);
}


function mdown()
{
    mdflag=true;
    while(mdflag)
    document.getElementById("testdiv").innerHTML = count++;

}
function mup()
{
    mdflag = false;
}

I'm wanting to run code while the mouse is down, i cant find anything to suggest i can do while(mousedown) so i've tryed making a flag for mousedown which is reset on mouse up however i beleive the while loop is whats causing me to go get stuck in an infinite loop.我想在鼠标按下时运行代码,我找不到任何建议我可以在 while(mousedown) 中执行的操作,所以我尝试为 mousedown 制作一个标志,该标志在鼠标按下时重置,但是我相信 while 循环是什么导致我陷入无限循环。

Any advice to help with what i'm trying to acheive?有什么建议可以帮助我实现目标吗?

You have to invoke the mousedown activity in some reasonable interval.您必须在某个合理的时间间隔内调用 mousedown 活动。 I'd do this:我会这样做:

var mousedownID = -1;  //Global ID of mouse down interval
function mousedown(event) {
  if(mousedownID==-1)  //Prevent multimple loops!
     mousedownID = setInterval(whilemousedown, 100 /*execute every 100ms*/);


}
function mouseup(event) {
   if(mousedownID!=-1) {  //Only stop if exists
     clearInterval(mousedownID);
     mousedownID=-1;
   }

}
function whilemousedown() {
   /*here put your code*/
}
//Assign events
document.addEventListener("mousedown", mousedown);
document.addEventListener("mouseup", mouseup);
//Also clear the interval when user leaves the window with mouse
document.addEventListener("mouseout", mouseup);

You can't do that, as your function must end before another event is processed, but you could repetitively call a function until the mouse is up :您不能这样做,因为您的函数必须在处理另一个事件之前结束,但是您可以重复调用一个函数,直到鼠标抬起:

var timer;
document.addEventListener("mousedown", function(){
     timer=setInterval(function(){
          document.getElementById("testdiv").innerHTML = count++;
     }, 100); // the above code is executed every 100 ms
});
document.addEventListener("mouseup", function(){
    if (timer) clearInterval(timer)
});

You need to use setInterval to execute your function and clearInternal to stop您需要使用 setInterval 来执行您的功能并使用 clearInternal 来停止

let interval = setInterval(function(){
    console.log("executing...");
}, 0);


document.addEventListener("mouseup", function(){
    clearInterval(interval); 
    console.log('End'); 
});

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

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