嗨,我对javascript很陌生。我希望能够在用户单击 Canvas 上的点(短按)时触发一个事件,如果按住该点并保持1500毫秒,我应该具有其他功能。我应该认识到在完成mouseup之前的长按。
例如:
el.addEventListener("mousedown", doMouseDown, false); el.addEventListener("mouseup", update, false);
function doMouseDown()
{
if (short press)
functionality of shortpress
if (longpress)
functionality of long press
}
function update()
//do some update of coordinates
最佳答案
要使它正常工作,需要考虑几个关键:
您可以通过在处理程序代码中引用
this
来使处理程序通用。这样,您可以将其附加到任何元素。 mouseup的全局处理程序仅添加一次,它将使用跟踪的目标来区分是哪个元素导致了mousedown。计时器调用的代码将具有元素上下文绑定(bind)(bind()
),因此我们也可以使用通用的longpress处理程序来处理源元素(请参见下面的演示)。例子
var d = document.querySelectorAll("div"),
isDown = false,
isLong = false,
target, // which element was clicked
longTID; // so we can cancel timer
// add listener for elements
d[0].addEventListener("mousedown", handleMouseDown);
d[1].addEventListener("mousedown", handleMouseDown);
d[2].addEventListener("mousedown", handleMouseDown);
// mouseup need to be monitored on a "global" element or we might miss it if
// we move outside the original element.
window.addEventListener("mouseup", handleMouseUp);
function handleMouseDown() {
this.innerHTML = "Mouse down...";
isDown = true; // button status (any button here)
isLong = false; // longpress status reset
target = this; // store this as target element
clearTimeout(longTID); // clear any running timers
longTID = setTimeout(longPress.bind(this), 1500); // create a new timer for this click
};
function handleMouseUp(e) {
if (isDown && isLong) { // if a long press, cancel
isDown = false; // clear in any case
e.preventDefault(); // and ignore this event
return
}
if (isDown) { // if we came from down status:
clearTimeout(longTID); // clear timer to avoid false longpress
isDown = false;
target.innerHTML = "Normal up"; // for clicked element
target = null;
}
};
function longPress() {
isLong = true;
this.innerHTML = "Long press";
// throw custom event or call code for long press
}
div {background:#ffe;border:2px solid #000; width:200px;height:180px;
font:bold 16px sans-serif;display:inline-block}
<div>Click and hold me...</div>
<div>Click and hold me...</div>
<div>Click and hold me...</div>
关于javascript - 单击后如何检测鼠标按钮是否被按下一定时间,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30247497/