使用 javascript 在 x/y 坐标处模拟点击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10305477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simulate click at x/y coordinates using javascript
提问by Ahmed Hafez
How can I simulate a click at x/y co-ordinates using javascript or jquery?
如何使用 javascript 或 jquery 在 x/y 坐标处模拟点击?
I will use the script multiple times and I want the script to click on postion one then postion two then three then four and so one.
我将多次使用该脚本,并且我希望该脚本依次单击位置一、位置二、三、四等等。
It is better without moving the mouse cursor, but if it has to move then that is fine as well.
最好不移动鼠标光标,但如果它必须移动,那也没关系。
回答by Prestaul
This can actually be accomplished with the document.elementFromPoint
method. A jQuery example:
这实际上可以通过该document.elementFromPoint
方法来完成。一个 jQuery 示例:
function simulateClick(x, y) {
jQuery(document.elementFromPoint(x, y)).click();
}
simulateClick(100, 250);
simulateClick(400, 250);
Edit:Here is a working example: http://jsfiddle.net/z5YjY/
编辑:这是一个工作示例:http: //jsfiddle.net/z5YjY/
回答by Alex
On a second take, I'd share my experiences, and update Prestaul's answer.
第二次,我会分享我的经验,并更新 Prestaul 的答案。
In most cases, you don't just want to click on an element to induce the 'onclick' event, but you would like to use the click info for something (eg.: move a slider there, or put a popup at that exact place).
在大多数情况下,您不只是想点击一个元素来引发 'onclick' 事件,而是想将点击信息用于某些事情(例如:在那里移动一个滑块,或者在那个确切位置放置一个弹出窗口地方)。
I'm mostly using vanilla js, but it blends well with $.
我主要使用 vanilla js,但它与 $ 很好地融合在一起。
function simulateClick(x, y) {
var clickEvent= document.createEvent('MouseEvents');
clickEvent.initMouseEvent(
'click', true, true, window, 0,
0, 0, x, y, false, false,
false, false, 0, null
);
document.elementFromPoint(x, y).dispatchEvent(clickEvent);
}
Basically this will pass down the correct pageX / pageY through the event, for further use.
基本上这将通过事件传递正确的 pageX / pageY,以供进一步使用。
I have updated the fiddle as well, to show a use of these coords: http://jsfiddle.net/V4CdC/
我也更新了小提琴,以展示这些坐标的使用:http: //jsfiddle.net/V4CdC/