简体   繁体   English

如何单击页面上的坐标?

[英]How do I click coordinate on page?

This is probably such a simple question, but after reading a few tutorials and other posts on Stack Overflow, I couldn't get what I was looking for. 这可能是一个简单的问题,但在阅读Stack Overflow上的一些教程和其他帖子后,我无法得到我想要的东西。

Using the .click() function in jQuery, I want to click a specific X , and Y location on the page. 使用jQuery中的.click()函数,我想单击页面上的特定XY位置。 All I found were tutorials on how to find coordinates, but not specifically click them. 我找到的只是关于如何找到坐标的教程,但没有特别点击它们。

See Using jQuery to find an element at a particular position? 请参阅使用jQuery查找特定位置的元素?

To get the element under the point (x,y) use document.elementFromPoint. 要获取点(x,y)下的元素,请使用document.elementFromPoint。 You can wrap this in a jquery object and invoke the click handler to simulate an actual click. 您可以将其包装在jquery对象中,并调用单击处理程序来模拟实际的单击。

function click(x,y) {
   var element = document.elementFromPoint(x,y);
   $(element).click();
}

Be careful of the drawbacks using elementFromPoint regarding absolute coordinates vs viewport relative coordinates http://www.zehnet.de/2010/11/19/document-elementfrompoint-a-jquery-solution/ 请注意使用elementFromPoint关于绝对坐标与视口相对坐标的缺点http://www.zehnet.de/2010/11/19/document-elementfrompoint-a-jquery-solution/

Here's a nice little tutorial on jQuery's documentation. 这是关于jQuery文档的一个很好的小教程 Essentially it goes like so: 基本上它是这样的:

$('#chosen_element').click(function(e){
    alert('X position is:' + e.pageX + 'Y position is:' + e.pageY);
});

Just bind a click event to an element, then handle it accordingly... Nothing out of the norms. 只需将click事件绑定到一个元素,然后相应地处理它......没有任何规范。 As an example: 举个例子:

$(el).bind('click', function(event){
     var x = event.pageX,
         y = event.pageY;

     console.log(x + " : " + y); // change to alert to see results with no console
});

You don't have to worry about proper handling of getting the mouse offsets. 您不必担心获得鼠标偏移的正确处理。 jQuery fixes it up so you can simple say event.pageX / event.pageY to get the position in any browser. jQuery修复了它,所以你可以简单地说event.pageX / event.pageY来获取任何浏览器中的位置。 In the example above, I just set x and y as local variables, but if you have to use it outside the scope of the callable, you can just make them global. 在上面的例子中,我只是将x和y设置为局部变量,但是如果必须在可调用范围之外使用它,则可以将它们设置为全局变量。 Note that this logs the coordinates to your web console and if you can't access that, change console.log to something like alert to make sure everything is working fine. 请注意,这会将坐标记录到Web控制台,如果您无法访问它,请将console.log更改为alert ,以确保一切正常。

Edit: After rereading your question, my answer changes: 编辑:重新阅读您的问题后,我的回答发生了变化:

You can target a specific element by setting it's x and y coordinates using document.elementFromPoint . 您可以使用document.elementFromPoint设置其x和y坐标来定位特定元素。 It seems supported in major browsers according to this page . 根据此页面 ,主流浏览器似乎支持它。

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

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