ShadowRoot: elementFromPoint() 方法

非标准:此特性未标准化。我们不建议在生产环境中使用非标准特性,因为它们浏览器支持有限,并且可能会更改或被移除。但是,在没有标准选项的特定情况下,它们可以是合适的替代方案。

elementFromPoint() 方法在 ShadowRoot 对象上可用,它会返回指定坐标处最顶层的 shadow root 元素(即在显示 z 顺序中最高且能够接收指针事件的 shadow root)。pointer-events 设置为 none 的 shadow root 元素将被忽略。

如果指定点超出 shadow root 的边界,则结果为 undefined

语法

js
elementFromPoint(x, y)

参数

x

点的水平坐标,相对于当前 视口 的左边缘。

y

点的垂直坐标,相对于当前视口的顶部边缘。

返回值

一个 Element;如果存在,则是在指定坐标处的最顶层 shadow root 元素。

示例

在此示例中,假设 HTML 中存在一个 <template>,我们定义了一个 <my-custom-element>。如果附加的自定义元素紧邻视口的左上角,或者其任何部分与该角重叠,那么在自定义元素中位于该点的最顶层元素将有一个细的、虚线的红色边框。

js
customElements.define(
  "my-custom-element",
  class extends HTMLElement {
    constructor() {
      super();
      const templateContent = document.getElementById(
        "my-custom-element-template",
      ).content;
      const sRoot = this.attachShadow({ mode: "open" });
      sRoot.appendChild(templateContent.cloneNode(true));

      // get the topmost element in the top left corner of the viewport
      const srElement = this.shadowRoot.elementFromPoint(0, 0);
      // apply a border to that element
      srElement.style.border = "1px dashed red";
    }
  },
);

规范

不属于任何标准。

浏览器兼容性

另见