鼠标按下时的 JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15505272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript while mousedown
提问by Larry
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?
有什么建议可以帮助我实现目标吗?
回答by Tomá? Zato - Reinstate Monica
You have to invoke the mousedown activity in some reasonable interval. I'd do this:
您必须在某个合理的时间间隔内调用 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);
回答by drunken bot
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)
});