ShadowRoot: adoptedStyleSheets 属性

Baseline 已广泛支持

此功能已成熟,并可在许多设备和浏览器版本上运行。自 2023 年 3 月以来,它已在各种浏览器中可用。

ShadowRoot 接口的 adoptedStyleSheets 属性用于设置一组用于 shadow DOM 子树的构造样式表。

注意: 构造样式表是通过使用 CSSStyleSheet() 构造函数 以编程方式创建的样式表(与用户代理在脚本中导入样式表、使用 <style>@import 导入、或通过 <link> 链接的样式表相比)。

同一个构造样式表可以被多个 ShadowRoot 实例以及父文档(使用 Document.adoptedStyleSheets 属性)采纳。更改采纳的样式表将影响所有采纳对象。

adoptedStyleSheets 属性中的样式表会与 shadow DOM 的其他样式表一起被考虑。为了确定任何元素的最终计算 CSS,它们被认为是在 shadow DOM 中的其他样式表(ShadowRoot.styleSheets之后 添加的。

只有使用 CSSStyleSheet() 构造函数 创建的,并且在 shadow root 的父 Document 范围内创建的样式表才能被采纳。

该值是一个 CSSStyleSheet 实例的数组,这些实例必须是在 shadow root 的父 Document 上下文中,使用 CSSStyleSheet() 构造函数创建的。

如果需要修改数组,请使用原地修改方法,如 push()CSSStyleSheet 实例本身也可以修改,这些更改将适用于样式表被采纳的任何地方。

在规范的早期版本中,数组是不可修改的,因此添加新样式表的唯一方法是将一个新数组赋值给 adoptedStyleSheets

示例

采纳样式表

下面的代码首先展示了一个构造的样式表,然后调用 CSSStyleSheet.replaceSync() 来向该样式表添加一条规则。

js
// Create an empty "constructed" stylesheet
const sheet = new CSSStyleSheet();
// Apply a rule to the sheet
sheet.replaceSync("a { color: red; }");

然后我们创建一个 ShadowRoot,并将样式表对象作为数组传递给 adoptedStyleSheets

js
// Create an element in the document and then create a shadow root:
const node = document.createElement("div");
const shadow = node.attachShadow({ mode: "open" });

// Adopt the sheet into the shadow DOM
shadow.adoptedStyleSheets = [sheet];

在样式表被添加到数组后,我们仍然可以修改它们。下面我们使用 CSSStyleSheet.insertRule() 向同一个样式表添加一条新规则。

js
sheet.insertRule("* { background-color: blue; }");
// The document will now have blue background.

添加一个新样式表

可以通过使用 adoptedStyleSheets.push() 将新样式表追加到文档或 shadow root。

js
const extraSheet = new CSSStyleSheet();
extraSheet.replaceSync("p { color: green; }");

// Concat the new sheet.
shadow.adoptedStyleSheets.push(extraSheet);

规范

规范
CSS 对象模型 (CSSOM)
# dom-documentorshadowroot-adoptedstylesheets

浏览器兼容性

另见