xde*_*000 2 javascript events dom
如何模拟DIV上的onclick事件只传递X,Y坐标???
如果我试图明确表示dispatchEvent函数想要引发事件的对象...但是那么在事件创建中传递坐标是什么意思????
谢谢
clientX和clientY参数是相对于处理事件的元素的位置,因此您需要知道click事件将要进入的元素.
如果要根据窗口坐标模拟对未知元素的单击,则需要在该位置找到该元素.在IE和Firefox 3中,您可以使用document.elementFromPoint(x, y).我不知道在其他浏览器中有什么办法,除了遍历页面中的元素,查看它们的位置/大小以确定坐标处的内容.
您的代码看起来像这样:
function simulateClick(x, y) {
var el = getElementFromPoint(x, y);
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
1, 0, 0,
calculateClientX(el, x), calculateClientY(el, y),
false, false, false, false, 0, null);
el.dispatchEvent(evt);
}
Run Code Online (Sandbox Code Playgroud)
getElementFromPoint将使用document.elementFromPoint或迭代所有元素.calculateClientX/Y将计算相对于元素的点击坐标.