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①

浏览器兼容性