0

如何从 HTML 元素中获取相对于屏幕的 x,y 坐标?我正在使用getBoundingClientRect()下面的 x,y,但正如您在打击图像中看到的那样,如果我使用将光标移动到这个 x,y 位置,则光标位于 0 和 + 按钮之间的中间,而不是 5 按钮,这是目标按钮。我错过了什么?

JS代码:

var e = document.querySelector('input[id=five]');"
var r = e.getBoundingClientRect();
var x = r.x;
var y = r.y;
MoveMouseTo(x,y); // imaginary call, the real cursor move is done by C# but I can share the code, as needed.

图片:

在此处输入图像描述

注意:如果这个附加信息可能有帮助,它是一个带有嵌入式浏览器的 C# 应用程序。

4

2 回答 2

0
const getCoords = (e) => {
var x = e.clientX 
var y = e.clientY
var xx = e.screenX
var yy = e.screenY

console.log(x, y, "client")
console.log(xx, yy, "screen")
}

您将要将此函数分配给onmousemove包含计算器 UI 的最外层 div 的事件。这至少应该向您展示屏幕 X、Y 和客户端 X、Y 之间的区别

https://www.w3schools.com/code/tryit.asp?filename=FVXZOK1SPTR0

于 2018-10-05T20:07:45.357 回答
0

您可以尝试在元素上添加事件侦听器并使用该事件来检索鼠标的坐标。

const $element = document.querySelector('input[id=five]');
$element.addEventListener('mousemove', handleMouseMove);
function handleMouseMove (event) {
  console.log('Offset from the screen coordinates', event.screenX, event.screenY);
  // The client refers to the element you are bound to;
  console.log('Offset from the client coordinates', event.clientX, event.clientY);
};
于 2018-10-05T21:06:56.247 回答