我有以下代码片段
$(document).mousedown(function(event) {
doSomething();
}
我可以成功捕获mousedown
事件。
我正在尝试执行以下操作:
mousedown
事件答案 0 :(得分:26)
像
这样的东西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;
});
答案 1 :(得分:19)
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 //
}
您还可以在clearInterval
事件上加mouseleave
。
答案 2 :(得分:5)
你实现了一些递归!
var mouseisdown = false;
$(document).mousedown(function(event) {
mouseisdown = true;
doSomething();
}).mouseup(function(event) {
mouseisdown = false;
});
function doSomething(){
//Code goes here
if (mouseisdown)
doSomething();
}
答案 3 :(得分:1)
您需要在mouseDown
上执行某些操作,开始执行某些操作并继续执行此操作直到mouseUp
事件被触发。
答案 4 :(得分:1)
使用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.
}
}
希望有所帮助!
答案 5 :(得分:1)
$(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);
}
}
});
答案 6 :(得分:0)
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
}
我发现这更方便。