简介
elementFromPoint
系列有两个方法:document.elementFromPoint
和 document.elementsFromPoint
(注意是 elements,多个“s”)。
document.elementFromPoint
获取指定坐标点最上面的元素,而 document.elementsFromPoint
获取指定坐标点下面的所有元素,包括 html
元素,body
元素取决于其是否在指定的坐标上。
签名
它们的签名分别为:
- elementFromPoint(x: number, y: number): Element
- elementsFromPoint(x: number, y: number): Array
示例
- 下面是一个在线示例:
See the Pen elementFromPoint by tcatche (@tcatche) on CodePen.
从示例中可以看出,返回的元素和位置顺序和其层叠的层级有关。
- 再看另一个实例,更改点击的元素的文字颜色:
See the Pen 更改点击元素的背景颜色 by tcatche (@tcatche) on CodePen.
注意
point-events
设置为none
的元素将被忽略。- 如果指定的坐标点在文档的可视范围外,或者坐标包含负数,那么结果返回 null 或 [] (与浏览器版本有关)。
- 如果指定的位置为匿名元素(如
::before
,::after
)或 滚动条,则返回其最近一个非匿名类型的祖先元素。