admin管理员组文章数量:1134586
Using Javascript how can I identify the element at a given position? Basically I'm looking to write a function that takes two input parameters (the x and y coordinates) and returns the html element at the position on the screen represented by the parameters.
Using Javascript how can I identify the element at a given position? Basically I'm looking to write a function that takes two input parameters (the x and y coordinates) and returns the html element at the position on the screen represented by the parameters.
Share Improve this question asked Aug 11, 2009 at 10:41 kjvkjv 11.3k35 gold badges102 silver badges141 bronze badges 1- 3 elementsFromPoint – Janus Troelsen Commented May 24, 2016 at 12:48
3 Answers
Reset to default 274document.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
You can use the native JavaScript elementFromPoint(x, y)
method, that returns the element at coordinates x,y in the viewport.
See the elementFromPoint w3c draft
And, a code sample:
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>
You can use setInterval()
to continuously check the element's hover event but it's not recommended, try to use .hover(...)
and css instead to enhance the application performance.
To get the topmost element at a specific position relative to the viewport, document.elementFromPoint(x, y)
can be used.
To obtain an array of all the elements at a specific position, use document.elementsFromPoint(x, y)
.
In both cases, x
is the horizontal coordinate which is relative to the left of the viewport and y
is the vertical coordinate which is relative to the top of the viewport.
本文标签: htmlGet element at specified positionJavaScriptStack Overflow
版权声明:本文标题:html - Get element at specified position - JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736822433a1954345.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论