← 中文资源

简体中文版本

attachShadow 隔离标记与样式

attachShadow 把标记与查询隔离在影子根内,内部样式不会漏到文档;closed 模式连 shadowRoot 引用一并隐藏。

阅读英文原文

实现说明

各个操作都建立在顶层绑定之上:stage、host、root、outside。

使用要点

  • 浏览器才是这里的运行环境:document 在 Node 里拿不到。
  • 直接运行文件,输出会带上标签,比如 stage p count:、shadow p count:、stage finds shadow p:——输出的每一行都能指回产生它的那次调用。

常见问题

「attachShadow 隔离标记与样式」能在裸 Node.js 里跑吗?

不能——这类 API 归浏览器环境所有(document),Node 里不存在。请在页面或 DevTools 控制台中运行。

核心语句

root.innerHTML = '<style>p { font-weight: bold; }</style><p>inside shadow</p>';
const root = host.attachShadow({ mode: 'open' });
const sealed = document.createElement('div');

代码示例

const stage = document.createElement('div');
document.body.append(stage);

// open-mode shadow root: the markup and styles live inside a boundary that
// normal DOM queries cannot cross
const host = document.createElement('div');
stage.append(host);
const root = host.attachShadow({ mode: 'open' });
root.innerHTML = '<style>p { font-weight: bold; }</style><p>inside shadow</p>';

// document-level queries cannot see past the shadow boundary
console.log('stage p count:', stage.querySelectorAll('p').length);
console.log('shadow p count:', root.querySelectorAll('p').length);
console.log('stage finds shadow p:', stage.querySelector('p') === null);

// styles defined inside the shadow do not leak onto light DOM siblings
const outside = document.createElement('p');
stage.append(outside);
console.log('outside styled by shadow:', getComputedStyle(outside).fontWeight === 'bold');

// closed mode additionally withholds the shadowRoot reference
const sealed = document.createElement('div');
sealed.attachShadow({ mode: 'closed' });
console.log('closed shadowRoot:', sealed.shadowRoot);