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";
    }
  },
);

規範

不屬於任何標準。

瀏覽器相容性

另見