mousedown时的JavaScript

Lar*_*rry 11 javascript while-loop 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;
}
Run Code Online (Sandbox Code Playgroud)

我想要在鼠标停止时运行代码,我无法找到任何建议我可以做的同时(mousedown)所以我尝试为mousedown制作一个标志,这是在鼠标上重置然而我相信while循环是什么导致我陷入无限循环.

有什么建议可以帮助我实现的目标吗?

Tom*_*ica 14

您必须在某个合理的时间间隔内调用mousedown活动.我这样做:

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);
Run Code Online (Sandbox Code Playgroud)

  • @TomášZato顺便说一下,在调用`clearInterval()`之前,你不一定要测试`null`.与[`clearTimeout()`](https://developer.mozilla.org/en-US/docs/DOM/window.clearTimeout#Notes)一样:"*传递无效ID [...]没有任何效果(并没有抛出异常).*"虽然这些方法实际上并未标准化,但几乎所有当前的实现都遵循这一点. (2认同)

dru*_*bot 5

你不能这样做,因为你的函数必须在处理另一个事件之前结束,但你可以重复调用一个函数直到鼠标启动:

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)
});
Run Code Online (Sandbox Code Playgroud)