示例工程 43-shadow-dom
43-shadow-dom/demo-01-encapsulation/index.html
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>样式封装演示</title>
<style>
body { margin: 0; padding: 32px; background: #f8fafc; color: #0f172a; font-family: system-ui, sans-serif; line-height: 1.7; }
.box { max-width: 720px; margin-bottom: 16px; padding: 18px; border: 1px solid #e2e8f0; border-radius: 12px; background: #fff; }
h1 { margin: 0 0 16px; font-size: 28px; }
h2 { margin: 0 0 8px; font-size: 17px; }
p { margin: 0 0 10px; color: #334155; }
/* 这条规则进不去 Shadow,颜色不会变红 */
x-box .inner { color: #dc2626; }
x-box { display: block; margin: 8px 0; }
.theme { --inner-color: #7c3aed; }
code { padding: 1px 5px; border-radius: 4px; background: #f1f5f9; font-family: ui-monospace, monospace; }
ol { margin: 8px 0 0; padding-left: 22px; color: #334155; font-size: 14px; }
</style>
</head>
<body>
<h1>样式封装</h1>
<div class="box">
<h2>全局选择器进不去</h2>
<p>外部写了 <code>x-box .inner { color: red }</code>,但内部文字仍是自己的颜色。</p>
<x-box>默认主题</x-box>
</div>
<div class="box theme">
<h2>自定义属性可以穿透</h2>
<p>宿主设置 <code>--inner-color: #7c3aed</code>,内部用 <code>var()</code> 读取。</p>
<x-box>继承主题色</x-box>
</div>
<div class="box">
<h2>open 与 closed</h2>
<p>两个元素内部结构相同,但一个可以从外部拿到 <code>shadowRoot</code>,另一个拿不到。</p>
<x-box id="open-box">open 模式</x-box>
<x-box id="closed-box" mode="closed">closed 模式</x-box>
<ol id="log"></ol>
</div>
<script>
class XBox extends HTMLElement {
constructor() {
super();
const mode = this.getAttribute("mode") === "closed" ? "closed" : "open";
const root = this.attachShadow({ mode });
root.innerHTML = `
<style>
:host { display: block; padding: 10px 12px; border: 1px solid #cbd5e1; border-radius: 8px; background: #f8fafc; }
.inner { color: var(--inner-color, #0f172a); font-weight: 600; }
</style>
<span class="inner"><slot></slot></span>
`;
}
}
customElements.define("x-box", XBox);
const log = document.getElementById("log");
const add = (text) => {
const li = document.createElement("li");
li.textContent = text;
log.append(li);
};
add("open 元素 shadowRoot: " + Boolean(document.getElementById("open-box").shadowRoot));
add("closed 元素 shadowRoot: " + Boolean(document.getElementById("closed-box").shadowRoot));
add("closed 元素内部仍正常工作,只是外部拿不到引用");
</script>
</body>
</html>