文档:adoptedStyleSheets 属性
Document 接口的 adoptedStyleSheets 属性用于设置一个由构造样式表组成的数组,供文档使用。
注意: 构造样式表是使用 CSSStyleSheet() 构造函数以编程方式创建的样式表(与用户代理在从脚本导入样式表、使用 <style> 和 @import 导入或通过 <link> 链接时创建的样式表不同)。
相同的构造样式表也可以使用 ShadowRoot.adoptedStyleSheets 属性与一个或多个 ShadowRoot 实例共享。更改已采用的样式表将影响所有采用它的对象。
属性中的样式表与文档的其他样式表一起使用 CSS 层叠算法进行评估。在规则解析考虑样式表顺序时,adoptedStyleSheets 被假定在 Document.styleSheets 中的样式表之后。
只有在当前 Document 的上下文中使用 CSSStyleSheet() 构造函数创建的样式表才能被采用。
值
该值是一个 CSSStyleSheet 实例数组,这些实例必须在同一个 Document 的上下文中,使用 CSSStyleSheet() 构造函数创建。
如果需要修改数组,请使用 push() 等就地修改。CSSStyleSheet 实例本身也可以被修改,这些更改将应用于采用该样式表的所有地方。
在规范的早期版本中,该数组不可修改,因此添加新样式表的唯一方法是为 adoptedStyleSheets 分配一个新数组。
异常
NotAllowedErrorDOMException-
数组中的某个
CSSStyleSheet实例不是使用CSSStyleSheet()构造函数创建的,或者是在与当前文档不同的文档中构造的,例如在框架中的文档。
示例
采用样式表
下面的代码展示了一个样式表被构造,然后调用 CSSStyleSheet.replaceSync() 来向样式表添加一个规则。然后将样式表添加到一个数组并赋值给 adoptedStyleSheets 属性。
// Create an empty "constructed" stylesheet
const sheet = new CSSStyleSheet();
// Apply a rule to the sheet
sheet.replaceSync("a { color: red; }");
// Apply the stylesheet to a document
document.adoptedStyleSheets.push(sheet);
我们可以使用 CSSStyleSheet.insertRule() 向样式表添加新规则。
sheet.insertRule("* { background-color: blue; }");
// The document will now have blue background.
与 Shadow DOM 共享样式表
我们可以以类似的方式将样式表共享给 Shadow Root。
// 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 same sheet into the shadow DOM
shadow.adoptedStyleSheets = [sheet];
规范
| 规范 |
|---|
| CSS 对象模型 (CSSOM) # dom-documentorshadowroot-adoptedstylesheets |
浏览器兼容性
加载中…