ShadowRoot: adoptedStyleSheets 属性
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() 来向该样式表添加一条规则。
// Create an empty "constructed" stylesheet
const sheet = new CSSStyleSheet();
// Apply a rule to the sheet
sheet.replaceSync("a { color: red; }");
然后我们创建一个 ShadowRoot,并将样式表对象作为数组传递给 adoptedStyleSheets。
// 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() 向同一个样式表添加一条新规则。
sheet.insertRule("* { background-color: blue; }");
// The document will now have blue background.
添加一个新样式表
可以通过使用 adoptedStyleSheets.push() 将新样式表追加到文档或 shadow root。
const extraSheet = new CSSStyleSheet();
extraSheet.replaceSync("p { color: green; }");
// Concat the new sheet.
shadow.adoptedStyleSheets.push(extraSheet);
规范
| 规范 |
|---|
| CSS 对象模型 (CSSOM) # dom-documentorshadowroot-adoptedstylesheets |
浏览器兼容性
加载中…