Javascript jQuery连续鼠标向下
我有以下代码片段Javascript jQuery连续鼠标向下,javascript,jquery,Javascript,Jquery,我有以下代码片段 $(document).mousedown(function(event) { doSomething(); } 我可以成功捕获mousedown事件 我正在努力做到以下几点: 捕获第一个mousedown事件 我想检测用户是否仍在按住鼠标,以便我可以执行其他操作 您需要在mouseDown上执行类似操作,开始执行某些操作并继续执行,直到触发mouseUp事件 var mouseStillDown = false; $(document).mousedown(fun
$(document).mousedown(function(event) {
doSomething();
}
我可以成功捕获mousedown
事件
我正在努力做到以下几点:
mousedown
事件您需要在
mouseDown
上执行类似操作,开始执行某些操作并继续执行,直到触发mouseUp
事件
var mouseStillDown = false;
$(document).mousedown(function(event) {
mouseStillDown = true;
doSomething();
});
function doSomething() {
if (!mouseStillDown) { return; } // we could have come back from
// SetInterval and the mouse is no longer down
// do something
if (mouseStillDown) { setInterval("doSomething", 100); }
}
$(document).mouseup(function(event) {
mouseStillDown = false;
});
你应该实现一些递归
var mouseisdown = false;
$(document).mousedown(function(event) {
mouseisdown = true;
doSomething();
}).mouseup(function(event) {
mouseisdown = false;
});
function doSomething(){
//Code goes here
if (mouseisdown)
doSomething();
}
使用mousedown事件设置标志,使用mouseup取消设置标志。然后,您可以简单地检查标志,看看它是否已设置 埃克斯马普
var mouseDownFlag = false;
$(document).mousedown(function(event) {
mouseDownFlag = true;
someFunc();
}
$(document).mouseup(function(event) {
mouseUpFlag = true;
}
var someFunc = function(){
if(mouseDownFLag){//only run this function when the mouse is clicked
// your code
setTimeout("somefunc()", 1000); //run this function once per second if your mouse is down.
}
}
希望有帮助
var int00; // declared here to make it visible to clearInterval.
$('#trigger').mousedown(function(){
int00 = setInterval(function() { repeatingfunction(); }, 50);
}).mouseup(function() {
clearInterval(int00);
});
function repeatingfunction() {
// This will repeat //
}
您还可以在mouseleave
事件上放置clearInterval
$(document).ready(function(){
var mouseStillDown = false;
$('#some_element').mousedown(function() {
do_something();
}).mouseup(function() {
clearInterval(mouseStillDown);
mouseStillDown = false;
});
function do_something() {
// add some code here that repeats while mouse down
if (!mouseStillDown) {
mouseStillDown = setInterval(do_something, 100);
}
}
});
我觉得这样做方便多了。我怎样才能继续这样做?使用setInterval()?更好的是:setInterval(“doSomething()”,100);您应该存储对间隔的引用,然后在再次调用setInterval之前清除它(如果需要),否则可能会导致多个间隔同时运行。如果我没有弄错的话,上面的代码将生成多个同时运行的间隔,不断创建更多的间隔,这真的很糟糕。正确的单间隔解决方案,然后清除是在这里:优雅的解决方案,但一个小的打字错误。。setInterval:)和一个更小的编辑器输入错误:其var int00;不是var int100;这不起作用,至少在我的环境中是这样。递归调用可防止触发mouseup事件,因此
mouseisdown
始终为true,完全阻塞UI。如果递归调用放在setTimeout
函数中,它就可以工作,但是我看不到使用这个解决方案而不是Janos提供的解决方案的好处。
let target = document.querySelector(".targetElement");
target.addEventListener('mousedown', event => {
target.addEventListener('mousemove',doStuff);
});
target.addEventListener('mouseup', event => {
target.removeEventListener('mousemove',doStuff);
});
function doStuff(event){
// code
}