示例工程 43-shadow-dom
43-shadow-dom/app/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>Shadow DOM · 样式与结构的封装边界</title>
<meta name="description" content="attachShadow、:host、::slotted、::part、CSS 自定义属性与事件重定向。" />
<style>
* { box-sizing: border-box; }
body {
margin: 0;
min-height: 100vh;
padding: 30px 20px 40px;
background: #f8fafc;
color: #0f172a;
font-family: system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
line-height: 1.7;
}
.page { width: min(100%, 800px); margin: 0 auto; }
.site-header { display: flex; justify-content: space-between; gap: 16px; padding-bottom: 14px; border-bottom: 1px solid #e2e8f0; }
.brand { font-weight: 700; letter-spacing: 0.14em; font-size: 13px; }
nav a { color: #2563eb; font-size: 13px; text-decoration: none; }
nav a + a { margin-left: 14px; }
main { padding: 22px 0; }
.eyebrow { margin: 0; color: #64748b; font-size: 11px; letter-spacing: 0.18em; }
h1 { margin: 6px 0 10px; font-size: clamp(30px, 6vw, 42px); line-height: 1.15; }
.lead { margin: 0 0 18px; color: #334155; font-size: 17px; }
section { margin-top: 22px; padding-top: 16px; border-top: 1px solid #e2e8f0; }
h2 { margin: 0 0 10px; font-size: 21px; }
p { margin: 0 0 12px; color: #334155; }
ul { margin: 8px 0 12px; padding-left: 24px; color: #334155; }
li + li { margin-top: 4px; }
.row { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin: 12px 0; }
/* 故意写一条想穿透 Shadow 的规则:不会生效 */
x-badge .dot { background: #dc2626; }
x-badge::part(label) { font-weight: 700; color: #1e3a8a; }
x-panel { display: block; }
.log { margin: 0; padding-left: 20px; font-size: 13px; color: #475569; }
code { padding: 1px 5px; border-radius: 4px; background: #f1f5f9; font-family: ui-monospace, Menlo, monospace; font-size: 0.92em; }
pre { margin: 10px 0 0; padding: 14px; overflow-x: auto; border-radius: 10px; background: #0f172a; color: #e2e8f0; font-size: 12px; line-height: 1.7; }
pre code { padding: 0; background: none; color: inherit; }
.note { padding: 12px 14px; border-left: 4px solid #2563eb; border-radius: 6px; background: #eff6ff; color: #1e3a8a; font-size: 14px; }
footer { margin-top: 24px; padding-top: 14px; border-top: 1px solid #e2e8f0; color: #64748b; font-size: 12px; }
@media (max-width: 560px) {
body { padding: 18px 14px 32px; }
.site-header { flex-direction: column; }
.row { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<div class="page">
<header class="site-header">
<span class="brand">SHADOW / 2026</span>
<nav aria-label="页内导航">
<a href="#host">封装</a>
<a href="#parts">部件</a>
<a href="#events">事件</a>
<a href="#rules">规则</a>
</nav>
</header>
<main>
<p class="eyebrow">LESSON / 43</p>
<h1>Shadow DOM</h1>
<p class="lead">
给元素挂一棵私有的 DOM 树:样式不外泄,外部选择器也进不来。封装带来稳定,也带来新的沟通方式。
</p>
<section id="host">
<h2>1. 样式封装</h2>
<p>下面两个徽章内容相同。全局规则 <code>x-badge .dot</code> 想改红点颜色,但进不去 Shadow。</p>
<div class="row">
<x-badge label="新" tone="blue">3 条新消息</x-badge>
<x-badge label="草稿" tone="amber">2 篇未发布</x-badge>
</div>
<x-panel accent="#7c3aed">
<span slot="title">构建状态</span>
<p>最近一次构建通过,用时 42 秒。</p>
</x-panel>
</section>
<section id="parts">
<h2>2. 开放的部件</h2>
<p>用 <code>part</code> 暴露可控部件,外部用 <code>::part()</code> 定制;用 <code>::slotted()</code> 定制插槽内容。</p>
<ul>
<li><code>part="label"</code>:徽章文字,外部加粗。</li>
<li><code>::slotted([slot="title"])</code>:面板标题。</li>
<li><code>--panel-accent</code>:主题色由宿主传入。</li>
</ul>
</section>
<section id="events">
<h2>3. 事件重定向</h2>
<p>点击计数器按钮,外部监听看到的 <code>event.target</code> 是宿主元素,不是内部按钮。</p>
<x-counter></x-counter>
<ul class="log" id="log" aria-live="polite">
<li>等待点击内部按钮…</li>
</ul>
</section>
<section id="rules">
<h2>4. 规则</h2>
<ul>
<li>一个元素只能挂一个 Shadow Root,挂了不能撤销。</li>
<li><code>mode: "open"</code> 可被 <code>shadowRoot</code> 访问,<code>"closed"</code> 只为封装。</li>
<li>样式默认隔离;需要外部定制时用 CSS 自定义属性、<code>::part</code> 或 <code>::slotted</code>。</li>
<li>事件默认穿过边界但会重定向 <code>target</code>;自定义事件用 <code>composed: true</code>。</li>
<li>焦点、选择与无障碍仍然跨边界工作,别把可聚焦内容藏起来。</li>
</ul>
</section>
</main>
<footer>
<p>示例数据为虚构,仅用于教学。</p>
</footer>
</div>
<script>
class XBadge extends HTMLElement {
static observedAttributes = ["tone"];
constructor() {
super();
const root = this.attachShadow({ mode: "open" });
root.innerHTML = `
<style>
:host {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 10px;
border: 1px solid #cbd5e1;
border-radius: 999px;
background: #fff;
font-size: 13px;
}
:host([tone="blue"]) { border-color: #bfdbfe; background: #eff6ff; color: #1e3a8a; }
:host([tone="amber"]) { border-color: #fde68a; background: #fffbeb; color: #92400e; }
.dot { width: 8px; height: 8px; border-radius: 50%; background: #2563eb; }
:host([tone="amber"]) .dot { background: #d97706; }
</style>
<span class="dot" part="dot"></span>
<span part="label"><slot></slot></span>
`;
}
}
customElements.define("x-badge", XBadge);
class XPanel extends HTMLElement {
static observedAttributes = ["accent"];
constructor() {
super();
const root = this.attachShadow({ mode: "open" });
root.innerHTML = `
<style>
:host {
display: block;
padding: 14px 16px;
border: 1px solid #e2e8f0;
border-top: 4px solid var(--panel-accent, #2563eb);
border-radius: 10px;
background: #fff;
}
::slotted([slot="title"]) {
display: block;
margin-bottom: 6px;
font-size: 16px;
font-weight: 700;
}
::slotted(p) { margin: 0; color: #475569; font-size: 14px; }
</style>
<slot name="title"></slot>
<slot></slot>
`;
}
attributeChangedCallback() {
this.style.setProperty("--panel-accent", this.getAttribute("accent") ?? "#2563eb");
}
}
customElements.define("x-panel", XPanel);
class XCounter extends HTMLElement {
constructor() {
super();
this.value = 0;
const root = this.attachShadow({ mode: "open" });
root.innerHTML = `
<style>
:host { display: inline-flex; align-items: center; gap: 10px; padding: 8px 10px; border: 1px solid #e2e8f0; border-radius: 10px; background: #fff; }
button { padding: 5px 12px; border: 1px solid #2563eb; border-radius: 6px; background: #2563eb; color: #fff; font: inherit; }
output { min-width: 2ch; font-variant-numeric: tabular-nums; }
</style>
<button type="button" part="button">+1</button>
<output part="value">0</output>
`;
const button = root.querySelector("button");
const output = root.querySelector("output");
button.addEventListener("click", () => {
this.value += 1;
output.textContent = String(this.value);
this.dispatchEvent(new CustomEvent("x-change", {
detail: { value: this.value },
bubbles: true,
composed: true,
}));
});
}
}
customElements.define("x-counter", XCounter);
const log = document.getElementById("log");
const add = (text) => {
const li = document.createElement("li");
li.textContent = text;
log.append(li);
};
log.replaceChildren();
const counter = document.querySelector("x-counter");
counter.addEventListener("x-change", (event) => {
add("外部收到 x-change,detail.value=" + event.detail.value);
add("event.target 是 " + event.target.tagName);
add("composedPath 长度 " + event.composedPath().length);
});
</script>
</body>
</html>