DocumentOrShadowRoot.elementFromPoint() - Web APIs 编辑

The elementFromPoint() method—available on both the Document and ShadowRoot objects—returns the topmost Element at the specified coordinates (relative to the viewport).

If the element at the specified point belongs to another document (for example, the document of an <iframe>), that document's parent element is returned (the <iframe> itself). If the element at the given point is anonymous or XBL generated content, such as a textbox's scroll bars, then the first non-anonymous ancestor element (for example, the textbox) is returned.

Elements with pointer-events set to none will be ignored, and the element below it will be returned.

If the method is run on another document (like an <iframe>'s subdocument), the coordinates are relative to the document where the method is being called.

If the specified point is outside the visible bounds of the document or either coordinate is negative, the result is null.

If you need to find the specific position inside the element, use Document.caretPositionFromPoint().

Syntax

const element = document.elementFromPoint(x, y)

Parameters

x
The horizontal coordinate of a point, relative to the left edge of the current viewport.
y
The vertical coordinate of a point, relative to the top edge of the current viewport.

Return value

The topmost Element object located at the specified coordinates.

Example

This example creates two buttons which let you set the current color of the paragraph element located under the coordinates (2, 2).

JavaScript

function changeColor(newColor) {
  elem = document.elementFromPoint(2, 2);
  elem.style.color = newColor;
}

The changeColor() method obtains the element located at the specified point, then sets that element's current foreground color property to the color specified by the newColor parameter.

HTML

<p id="para1">Some text here</p>
<button onclick="changeColor('blue');">Blue</button>
<button onclick="changeColor('red');">Red</button>

The HTML provides the paragraph whose color will be affected, as well as two buttons: one to change the color to blue, and another to change the color to red.

Result

Specifications

SpecificationStatus
Shadow DOM
The definition of 'elementsFromPoint()' in that specification.
Obsolete
CSS Object Model (CSSOM) View Module
The definition of 'elementsFromPoint()' in that specification.
Working Draft

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:63 次

字数:5404

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文