我希望能够将一个函数附加到一个元素上,该函数只有在该元素上单击指定时间后才会运行。
有几个( 1 、 2 、 3 )与在 javascript 中处理鼠标保持相关的问题;但这些问题要么使用 jQuery,要么与更特定的用例相关。
我想实现一些更通用的东西,我觉得对于这个问题应该有一个关于堆栈溢出的很好的答案。
最佳答案
这是我使用 window.setTimeout 得到的结果:
var mouseTimer;
var myVar;
function mouseDown() {
mouseTimer = window.setTimeout(myFunction,500); //set timeout to fire in 2 seconds when the user presses mouse button down
}
function myFunction(){ myVar = true;}
var div = document.getElementById("testBtn");
testBtn.addEventListener("mousedown", mouseDown);
document.body.addEventListener("mouseup", removeTimer);
function removeTimer(){
if(myVar) console.log("a");
if (mouseTimer) window.clearTimeout(mouseTimer);
myVar = false;
}
<button id="testBtn">Test</button>
关于javascript - 普通 JavaScript 中的单击并按住事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56149463/