[英]Why OnMouseDown Event occur once , how to handle mouse hold event
鼠标点击和鼠标按下之间的区别——鼠标点击只发生一次,但每次鼠标按下时都会发生鼠标按下
这是我的简单示例 - 我不知道为什么事件只发生一次,但是我使用的是鼠标按下而不是鼠标单击
<canvas id="drawhere" onmousedown="console.log('HH')" width="600" height="500"></canvas>
它只写了一次“HH”!! 再次上下鼠标 - 再写一次
当我的鼠标按下时,我需要在每个滴答声中写入它 - 任何帮助:))
我不使用 jquery ,只使用 javascript
mouseup
和mousedown
不应该连续发射。 它们旨在表示发生了单个动作。
但是,您可以使用在mousedown
触发并在mouseup
取消的自定义计时器(更具体地说是setInterval()
来实现此效果:
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);
#main { background-color:yellow; width: 300px; height: 100px; }
<div id="main">Press and hold the mouse down inside me!</div>
使用“onmousemove”代替“onmouseover”,我建议你在你的javascript代码中使用这样的函数:
document.getElementById("drawhere").addEventListener("mousemove", function(){
console.log("mouse event!");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.