简体   繁体   中英

How Can I Make a Javascript Program Simulate a Mouse Click?

I want to make a JavaScript program simulate a mouse click wherever the mouse is on a timed interval. I know of the

if(mouseIsPressed) 

and the

if(mouseDown) 

commands, but are there any commands that make my mouse automatically click, some kind of forceMouseDown command maybe?

If you just want to click a button, as I see from the comment, than just click the specific button with HTMLElement.click() in an interval.

Like this:

 var myButton = document.getElementById('my-button'); // Just for example var clickCount = 0; var clickStatus = document.getElementById('clicks'); setInterval(function(){ myButton.click(); clickStatus.innerText = ++clickCount; }, 2000) 
 <button id="my-button">My Button</button> <p>Clicks: <span id="clicks">0</span></p> 

Can use elementFromPoint() to identify top most element at current mouse position.

Combine that with a mousemove listener to track mouse position in page

var mousePos ={x:0,y:0}


setInterval(function(){  
  document.elementFromPoint(mousePos.x, mousePos.y).click()
}, 2000)

document.addEventListener('mousemove', function(e){
  mousePos.x = e.clientX;
  mousePos.y = e.clientY;  
});

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