实现说明
演示用的数据放在这几个模块级绑定中:sheet、host、root、lightP。
使用要点
- 用到了
document,需要在浏览器环境运行,Node 里直接跑会缺 API。 - 直接运行文件,输出会带上标签,比如
light DOM p styled:、shadow p styled:、update reached both adopters:——输出的每一行都能指回产生它的那次调用。
常见问题
「adoptedStyleSheets 共享可构造样式表」能在裸 Node.js 里跑吗?
不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。
核心语句
sheet.replaceSync('p { border-width: 2px; border-style: solid; }');
sheet.replaceSync('p { border-width: 1px; border-style: solid; }');
const root = host.attachShadow({ mode: 'open' });
代码示例
// A constructable stylesheet is one object serving many adopters
const sheet = new CSSStyleSheet();
sheet.replaceSync('p { border-width: 2px; border-style: solid; }');
const host = document.createElement('div');
document.body.append(host);
const root = host.attachShadow({ mode: 'open' });
root.innerHTML = '<p>in shadow</p>';
const lightP = document.createElement('p');
document.body.append(lightP);
// The same sheet instance is adopted by the document and the shadow root
document.adoptedStyleSheets = [sheet];
root.adoptedStyleSheets = [sheet];
const shadowP = root.querySelector('p');
console.log('light DOM p styled:', getComputedStyle(lightP).borderTopWidth === '2px');
console.log('shadow p styled:', getComputedStyle(shadowP).borderTopWidth === '2px');
// replaceSync rewrites the shared sheet; every adopter sees the update
sheet.replaceSync('p { border-width: 1px; border-style: solid; }');
console.log('update reached both adopters:',
getComputedStyle(lightP).borderTopWidth === '1px' &&
getComputedStyle(shadowP).borderTopWidth === '1px');
// Un-adoption removes its styles everywhere at once
document.adoptedStyleSheets = [];
root.adoptedStyleSheets = [];
console.log('removed everywhere:',
getComputedStyle(lightP).borderTopWidth === '0px' &&
getComputedStyle(shadowP).borderTopWidth === '0px');