示例工程 44-slots-templates
44-slots-templates/demo-01-named-slots/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; }
x-card { display: block; margin: 10px 0; }
ol { margin: 8px 0 0; padding-left: 22px; color: #334155; font-size: 13px; }
code { padding: 1px 5px; border-radius: 4px; background: #f1f5f9; font-family: ui-monospace, monospace; }
</style>
</head>
<body>
<h1>具名插槽</h1>
<div class="box">
<h2>填入三个位置</h2>
<x-card>
<strong slot="title">发布清单</strong>
<p>检查构建、截图与文档链接。</p>
<span slot="meta">2 分钟前更新</span>
</x-card>
</div>
<div class="box">
<h2>只填默认插槽</h2>
<x-card>
<p>标题与页脚走回退内容。</p>
</x-card>
</div>
<div class="box">
<h2>slotchange 记录</h2>
<ol id="log" aria-live="polite"></ol>
</div>
<template id="card-tpl">
<style>
:host { display: block; }
.card { padding: 12px 14px; border: 1px solid #e2e8f0; border-radius: 10px; background: #fff; }
.top { display: flex; justify-content: space-between; gap: 10px; }
::slotted([slot="title"]) { font-size: 15px; }
::slotted([slot="meta"]) { color: #64748b; font-size: 12px; }
.fallback { color: #94a3b8; font-size: 13px; }
.body { margin-top: 6px; font-size: 14px; color: #334155; }
.body ::slotted(p) { margin: 0; }
</style>
<article class="card">
<div class="top">
<slot name="title"><span class="fallback">无标题</span></slot>
<slot name="meta"><span class="fallback">无时间</span></slot>
</div>
<div class="body"><slot></slot></div>
</article>
</template>
<script>
class XCard extends HTMLElement {
constructor() {
super();
const tpl = document.getElementById("card-tpl");
this.attachShadow({ mode: "open" }).append(tpl.content.cloneNode(true));
}
}
customElements.define("x-card", XCard);
const log = document.getElementById("log");
const add = (text) => {
const li = document.createElement("li");
li.textContent = text;
log.append(li);
};
const cards = [...document.querySelectorAll("x-card")];
cards.forEach((card, index) => {
const slot = card.shadowRoot.querySelector('slot[name="title"]');
slot.addEventListener("slotchange", () => {
const nodes = slot.assignedNodes({ flatten: true });
add("卡片 " + (index + 1) + " 标题插槽: " + nodes.length + " 个节点,文本「" + nodes.map((n) => n.textContent).join("").trim() + "」");
});
add("卡片 " + (index + 1) + " 初始标题:" + (card.querySelector('[slot="title"]')?.textContent ?? "(回退)"));
});
</script>
</body>
</html>