setInterval(mouse, 20);
function mouse(){
if(onMouseDown == true){
//Code for when you are holding mouse down
}else{
//Code for when the mouse isn't being held
}
}
这是我的代码的基本思路。当按住鼠标左键时,我希望它执行设置代码,然后当鼠标没有按下时,它会执行另一个任务。我该怎么做呢。谢谢:))
答案 0 :(得分:3)
function detectLeftButton(evt) {
evt = evt || window.event;
var btn = evt.which || evt.button;
return (btn == 1);
}
document.onmousedown = function() {
if(detectLeftButton(this.event)) {
// Code when mouse is down
}
}
document.onmouseup = function() {
if(detectLeftButton(this.event)) {
// Code when mouse is not held
}
}
在上面的代码中,当人在网页的任何地方按下鼠标左键时,代码将被运行,当他按下它时,将执行另一组代码。 Fiddle (updated)
了解详情here。
希望有所帮助。
答案 1 :(得分:2)
使用mousedown和mouseup事件以及setInterval / clearInterval
(function(){
var downTimer = null;
var upTimer = null;
function runWhileDown(){
//code to run while mouse is down
}
function runWhileUp(){
//code to run while mouse is up
}
document.addEventListener("mousedown",function(){
//Stop the runWhileUp code from running
if(upTimer) clearInterval(upTimer);
//make sure the previous interval is stopped
if(downTimer) clearInterval(downTimer);
//start the new timer
downTimer = setInterval(runWhileDown,20);
});
document.addEventListener("mouseup",function(){
//Stop the runWhileDown code from running
if(downTimer) clearInterval(downTimer);
//make sure the previous interval is stopped
if(upTimer) clearInterval(upTimer);
//start the new timer
upTimer = setInterval(runWhileUp,20);
});
//If you need the runWhileUp code to run at the start
upTimer = setInterval(runWhileUp,20);
})();