简体   繁体   English

如何使Javascript程序模拟鼠标单击?

[英]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. 我想让一个JavaScript程序模拟鼠标在定时间隔内的任何地方单击。 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? 命令,但是有没有什么命令可以使我的鼠标自动单击,也许是某种forceMouseDown命令?

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. 如果您只想单击一个按钮(如我从评论中看到的),则只需单击HTMLElement.click()中的特定按钮即可。

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. 可以使用elementFromPoint()来标识当前鼠标位置上最上面的元素。

Combine that with a mousemove listener to track mouse position in page 将其与mousemove侦听器结合使用以跟踪鼠标在页面中的位置

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;  
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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