I would like to simulate a mouse move event. The setup is as follows
I have this element
<div class="target"></div>
Which in this test setup follows the mouse: DEMO
I have already a working simulation of the mousedown event (click the button). The code that generated this event looks like this:
function triggerMouseEvent (node, eventType) {
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent (eventType, true, true);
node.dispatchEvent (clickEvent);
}
But how do I create a fake movemove
event? Because I also need to provide a pageX and pageY for it. How do I provide this information when I create an event as shown above?
I've updated your example code to show how to create a mousemove
event. Note that your code uses the deprecated document.createEvent() , and you should consider replacing that with the newer MouseEvent , which I used in the part of the code I added.
const target = document.querySelector('.target'); document.querySelector('main') .addEventListener('mousemove', (e) => { if (e.clientY > 60) { target.style.top = (e.clientY - 25) + 'px'; } target.style.left = (e.clientX - 25) + 'px'; }); target.addEventListener('mousedown', () => { console.log('mouse down'); }) const butt = document.querySelector('.sim-move'); butt.addEventListener('click', () => { let evt = new MouseEvent("mousemove", { clientX: 150, clientY: 5, bubbles: true, cancelable: true, view: window }); let canceled = !target.dispatchEvent(evt); }); const butt1 = document.querySelector('.sim-down'); butt1.addEventListener('click', () => { triggerMouseEvent(target, 'mousedown'); }); function triggerMouseEvent (node, eventType) { var clickEvent = document.createEvent ('MouseEvents'); clickEvent.initEvent (eventType, true, true); node.dispatchEvent (clickEvent); }
html, body, main { height: 100%; padding: 0; margin: 0; } body { margin: 20px; } main { display: block; border: 1px solid #000; height: calc(100% - 42px); } div { position: absolute; top: 50%; left: 50%; width: 50px; height: 50px; background-color: green; }
<button class="sim-move">Simulate mousemove</button> <button class="sim-down">Simulate mousedown</button> <main> <div class='target'></div> </main>
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.