【问题标题】:JavaScript while mousedown鼠标按下时的 JavaScript
【发布时间】:2013-03-08 11:14:55
【问题描述】:
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;
}

我想在鼠标按下时运行代码,我找不到任何建议我可以做的事情 while(mousedown) 所以我尝试为 mousedown 制作一个标志,该标志在鼠标按下时重置但是我相信 while循环是什么导致我陷入无限循环。

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

【问题讨论】:

    标签: javascript while-loop mousedown


    【解决方案1】:

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

    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)
    });
    

    【讨论】:

    • 您也可以在外部范围内声明timer,就像OP对mdflag所做的那样,并将mouseup事件移出mousedown,因此它不会继续添加更多。
    • 你想过如果我按下按钮离开窗口会发生什么吗?
    【解决方案2】:

    您必须在某个合理的时间间隔内调用 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);
    

    【讨论】:

    • 我能问一下为什么 -1 与 0 并列使用吗?
    • 我不确定是否存在 0 的 id - 我习惯于使用 -1 来表示 null 值。在javascript中,您可以直接设置mousedownID = null并询问if(mousedownID===null)(确定使用===检查数据类型)。
    • @TomášZato 顺便说一句,您不必在调用clearInterval() 之前测试null。与clearTimeout() 一样:“传递无效 ID [...] 没有任何效果(并且不会引发异常)。”尽管这些方法实际上并未标准化,但几乎所有当前的实现遵循此。
    • 很高兴您能指出这一点。但是,如果clearTimeout== 运算符更快地检查ID,它仍然是可争议的。例如,它可能会遍历一组超时 ID,这样会更慢。
    • 这并不能很好地工作,因为 event 没有被更新。
    【解决方案3】:

    您需要使用 setInterval 来执行您的功能并使用 clearInternal 来停止

    let interval = setInterval(function(){
        console.log("executing...");
    }, 0);
    
    
    document.addEventListener("mouseup", function(){
        clearInterval(interval); 
        console.log('End'); 
    });
    

    【讨论】:

    • 这与醉酒机器人的回答有何不同或更好?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    相关资源
    最近更新 更多