获取指定位置的元素 - JavaScript

IT技术 javascript html dom
2021-01-16 18:01:58

使用 Javascript 如何识别给定位置的元素?基本上,我希望编写一个函数,该函数接受两个输入参数(x 和 y 坐标)并返回屏幕上由参数表示的位置处的 html 元素。

3个回答
我很惊讶这在 ie 5.5 中起作用并且今天没有那么多使用。
2021-03-27 18:01:58
我试过这种方法,它根据文档测量位置。我如何相对于父元素使用它?
2021-03-28 18:01:58
一个 jsfiddle 例子真的很棒!看起来很神奇!迫不及待想试试看!
2021-04-01 18:01:58
如果在坐标 x、y 处有一个框架或 iframe,您将获得框架,而不是该位置的元素。
2021-04-03 18:01:58

您可以使用原生 JavaScriptelementFromPoint(x, y)方法,该方法返回视口中坐标 x,y 处的元素。

查看elementFromPoint w3c 草案

并且,一个代码示例:

function changeColor(newColor) {
    // Get the element placed at coords (2, 2)
    var elem = document.elementFromPoint(2, 2);
    // Set the foreground color to the element
    elem.style.color = newColor;
}
<p id="para1">Change this text color using the following buttons.</p>
<button onclick="changeColor('blue');">Blue</button>
<button onclick="changeColor('red');">Red</button>

您可以使用setInterval()来持续检查元素的悬停事件但不建议使用,请尝试使用.hover(...)和 css 来提高应用程序性能。

要获取相对于视口的特定位置的最顶层元素,document.elementFromPoint(x, y)可以使用。

要获取特定位置的所有元素的数组,请使用document.elementsFromPoint(x, y)

在这两种情况下,x是相对于视口左侧的水平坐标和y相对于视口顶部的垂直坐标。