与 Shadow DOM 共享样式表
下面的代码展示了构造样式表,然后调用 CSSStyleSheet.replaceSync() 来向样式表中添加规则。
js// Create an empty "constructed" stylesheet
const sheet = new CSSStyleSheet();
// Apply a rule to the sheet
sheet.replaceSync("a { color: red; }");
然后,我们创建一个 ShadowRoot,并将样式表对象作为数组传递给 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() 向同一个样式表追加新规则。
jssheet.insertRule("* { background-color: blue; }");
// The document will now have blue background.
同一个样式表可以在同一文档中的多个 shadow 子树之间共享。更多示例请参阅 ShadowRoot.adoptedStyleSheets。