【发布时间】:2010-11-18 13:51:31
【问题描述】:
使用 Javascript 如何识别给定位置的元素?基本上我正在寻找一个函数,它接受两个输入参数(x 和 y 坐标)并返回参数表示的屏幕上位置的 html 元素。
【问题讨论】:
标签: javascript html dom
使用 Javascript 如何识别给定位置的元素?基本上我正在寻找一个函数,它接受两个输入参数(x 和 y 坐标)并返回参数表示的屏幕上位置的 html 元素。
【问题讨论】:
标签: javascript html dom
document.elementFromPoint(x, y)
document.elementsFromPoint(x, y)
https://drafts.csswg.org/cssom-view/#dom-document-elementfrompoint
https://developer.mozilla.org/en-US/docs/Web/API/Document/elementFromPoint https://developer.mozilla.org/en-US/docs/Web/API/Document/elementsFromPoint
【讨论】:
要获取相对于视口的特定位置的最顶部元素,可以使用document.elementFromPoint(x, y)。
要获取特定位置的所有元素的数组,请使用document.element<b><i>s</i></b>FromPoint(x, y)。
在这两种情况下,x 是相对于视口左侧的水平坐标,y 是相对于视口顶部的垂直坐标。
【讨论】:
您可以使用原生 JavaScript elementFromPoint(x, y) 方法,该方法返回视口中坐标 x,y 处的元素。
还有一个代码示例:
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代替以增强应用程序性能。
【讨论】: