为什么OnMouseDown事件只发生一次,如何处理鼠标按住事件

Ahm*_*sen 0 javascript event-handling mouseevent

鼠标单击和鼠标按下之间的区别 - 鼠标单击仅发生一次,但鼠标按下每次发生我的鼠标按下

这是我的简单示例 - 我不知道为什么该事件只发生一次,但是我使用的是鼠标按下而不是鼠标单击

<canvas id="drawhere" onmousedown="console.log('HH')" width="600" height="500"></canvas>
Run Code Online (Sandbox Code Playgroud)

它只写一次“HH”!再次上下移动鼠标 - 重新写入

当我的鼠标按下时,我需要在每次勾选时写入它 - 任何帮助:))

我不使用 jquery ,仅使用 javascript

Sco*_*cus 5

mouseup并且mousedown不应该连续射击。它们旨在表明单个操作已经发生。

但是,您可以使用自定义计时器(setInterval()更具体地说)来实现此效果,该计时器在 上触发mousedown并在 上取消mouseup

document.getElementById("main");

var timer = null;  // Variable to hold a reference to the timer

// Set up an event handler for mousedown
main.addEventListener("mousedown", function(evt){
  // Start a timer that fires a function at 50 millisecond intervals
  timer = setInterval(function(){
    // the function can do whatever you need it to
    console.log("Mouse is down!");
  }, 50);
});

// Set up a custom mouseup event handler for letting go 
// of the mouse inside the box or when mouse leaves the box.
function mouseDone(evt){
  clearInterval(timer);         // Cancel the previously initiated timer function
  console.log("Mouse is up or outside of box!");  // And, do whatever else you need to
}

// Bind the handlers:
main.addEventListener("mouseup", mouseDone);
main.addEventListener("mouseleave", mouseDone);
Run Code Online (Sandbox Code Playgroud)
#main {
  background-color:yellow;
  width: 300px;
  height: 100px;
}
Run Code Online (Sandbox Code Playgroud)
<div id="main">Press and hold the mouse down inside me!</div>
Run Code Online (Sandbox Code Playgroud)