简体   繁体   中英

Why OnMouseDown Event occur once , how to handle mouse hold event

the difference between mouse click and mouse down - that mouse click occurs only once , but mouse down occurs every tick my mouse is down

here's in my simple example - I don't know why the event occur only once , however I am using mouse down not mouse click

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

It writes 'HH' only once !! mouse up and down again - to write it again

I need it to be written every tick as my mouse is down - any help :))

I don't use jquery , javascript only

mouseup and mousedown are not suppose to continuously fire. They are meant to signal a single action has happened.

However, you could achieve this effect with a custom timer ( setInterval() to be more specific) that is triggered on mousedown and cancelled on 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);
 #main { background-color:yellow; width: 300px; height: 100px; }
 <div id="main">Press and hold the mouse down inside me!</div>

Use "onmousemove" instead "onmouseover" and I recommend you use a function like this in your javascript code:

document.getElementById("drawhere").addEventListener("mousemove", function(){
    console.log("mouse event!");
});

Working pen: http://codepen.io/parzibyte/full/ENzjvW/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM