Element: shadowRoot 屬性

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流瀏覽器均已支援。

Element.shadowRoot 只讀屬性表示由該元素託管的 shadow root。

使用 Element.attachShadow() 向現有元素新增 shadow root。

一個 ShadowRoot 物件例項,如果關聯的 shadow root 在附加時其 mode 設定為 closed,則返回 null。(有關更多詳細資訊,請參閱 Element.attachShadow())。

一些內建元素,例如 <input><img>,具有對指令碼關閉的使用者代理 shadow root。因此,它們的 shadowRoot 屬性始終為 null

示例

以下程式碼片段摘自我們的 生命週期回撥 示例(也可線上檢視),該示例建立了一個根據元素屬性中指定的尺寸和顏色顯示正方形的元素。

<custom-square> 元素的類定義內部,我們包含了一些生命週期回撥,它們呼叫外部函式 updateStyle(),該函式實際應用了元素的尺寸和顏色。您會看到我們將 this(自定義元素本身)作為引數傳遞給它。

js
class Square extends HTMLElement {
  connectedCallback() {
    console.log("Custom square element added to page.");
    updateStyle(this);
  }

  attributeChangedCallback(name, oldValue, newValue) {
    console.log("Custom square element attributes changed.");
    updateStyle(this);
  }
}

updateStyle() 函式本身中,我們使用 Element.shadowRoot 獲取對 shadow DOM 的引用。從這裡開始,我們使用標準的 DOM 遍歷技術來查詢 shadow DOM 中的 <style> 元素,然後更新其中找到的 CSS。

js
function updateStyle(elem) {
  const shadow = elem.shadowRoot;
  const childNodes = Array.from(shadow.childNodes);

  childNodes.forEach((childNode) => {
    if (childNode.nodeName === "STYLE") {
      childNode.textContent = `
        div {
          width: ${elem.getAttribute("l")}px;
          height: ${elem.getAttribute("l")}px;
          background-color: ${elem.getAttribute("c")};
        }
      `;
    }
  });
}

規範

規範
DOM
# ref-for-dom-element-shadowroot①

瀏覽器相容性