DocumentOrShadowRoot.elementFromPoint()

这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。

DocumentOrShadowRoot 接口的 elementFromPoint() 方法返回给定坐标点的顶端 element 。 

If the element at the specified point belongs to another document (for example, an iframe's subdocument), the subdocument'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.

如果指定的坐标点在文档的可视范围,或者两个坐标都是负数,那么结果返回 null

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

Syntax

var element = document.elementFromPoint(x, y);

Parameters

x
坐标点的横坐标。
y
坐标点的纵坐标。

Returns

在给定的坐标点处的顶端 Element(译者注:如果元素层叠的话,返回最上层的元素)。

Example

<!DOCTYPE html>
<html lang="en">
<head>
<title>elementFromPoint example</title>

<script>
function changeColor(newColor) {
  elem = document.elementFromPoint(2, 2);
  elem.style.color = newColor;
}
</script>
</head>

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

Demo

 

Specifications

Specification Status Comment
Shadow DOM
DocumentOrShadowRoot
Obsolete Initial definition.

Browser Compatibility

Update compatibility data on GitHub
DesktopMobile
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung Internet
elementFromPoint
Experimental
Chrome Full support 53
Notes
Full support 53
Notes
Notes Before Chrome 66, this method returned null when the element was a child of a host node. See issue 759947.
Edge Full support YesFirefox Full support 63IE Full support YesOpera Full support 40Safari Full support YesWebView Android Full support 53
Notes
Full support 53
Notes
Notes Before WebView 66, this method returned null when the element was a child of a host node. See issue 759947.
Chrome Android Full support 53
Notes
Full support 53
Notes
Notes Before Chrome 66, this method returned null when the element was a child of a host node. See issue 759947.
Firefox Android Full support 63Opera Android Full support 41Safari iOS Full support YesSamsung Internet Android Full support 6.0

Legend

Full support  
Full support
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.
See implementation notes.
See implementation notes.