mousedown时的JavaScript [英] JavaScript while mousedown
本文介绍了mousedown时的JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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;
}
我想在鼠标停机时运行代码,我找不到任何暗示我可以做的事情(mousedown)所以我试图为mousedown制作一个标志,它在鼠标上重置然而我相信while循环是什么导致我陷入无限循环。
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.
任何有关我正在努力实现的建议?
Any advice to help with what i'm trying to acheive?
推荐答案
你有在某个合理的时间间隔内调用mousedown活动。我这样做:
You have to invoke the mousedown activity in some reasonable interval. 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);
这篇关于mousedown时的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文