示例工程 42-custom-elements
42-custom-elements/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>自定义元素 · 从标签到组件</title>
<meta name="description" content="用 customElements.define 定义元素,处理属性、生命周期与可访问性。" />
<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; }
.demo { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin: 12px 0; }
user-card { display: block; }
user-card article { height: 100%; padding: 14px; border: 1px solid #e2e8f0; border-radius: 10px; background: #fff; }
user-card h3 { margin: 0 0 2px; font-size: 17px; }
user-card p { margin: 0; color: #64748b; font-size: 13px; }
x-meter { display: block; margin: 10px 0; }
x-meter .label { display: flex; justify-content: space-between; font-size: 13px; color: #475569; }
x-meter .track { height: 10px; margin-top: 6px; border-radius: 999px; background: #e2e8f0; overflow: hidden; }
x-meter .fill { height: 100%; border-radius: 999px; background: #2563eb; }
.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; }
.demo { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<div class="page">
<header class="site-header">
<span class="brand">WC / 2026</span>
<nav aria-label="页内导航">
<a href="#define">定义</a>
<a href="#attrs">属性</a>
<a href="#life">生命周期</a>
<a href="#rules">规则</a>
</nav>
</header>
<main>
<p class="eyebrow">LESSON / 42</p>
<h1>自定义元素</h1>
<p class="lead">
给页面定义一个新标签,浏览器会像原生元素一样解析、升级并调用你的生命周期方法。名字里必须有一个短横线。
</p>
<section id="define">
<h2>1. 一次定义</h2>
<p>标签先出现在 HTML 里,脚本定义后立即「升级」并渲染。</p>
<div class="demo">
<user-card name="林小满" role="维护者"></user-card>
<user-card name="周野" role="审校"></user-card>
</div>
<pre><code>class UserCard extends HTMLElement {
static observedAttributes = ["name", "role"];
connectedCallback() { this.render(); }
attributeChangedCallback() {
if (this.isConnected) this.render();
}
}
customElements.define("user-card", UserCard);</code></pre>
</section>
<section id="attrs">
<h2>2. 属性驱动</h2>
<p>属性是外部接口,变化时同步到内部结构与 ARIA 状态。</p>
<x-meter value="72" label="本周完成度"></x-meter>
<x-meter value="38" label="文档覆盖"></x-meter>
<button type="button" id="bump">完成度 +10</button>
<p class="note">进度条用 <code>role="progressbar"</code> 与 <code>aria-valuenow</code> 暴露给读屏。</p>
</section>
<section id="life">
<h2>3. 生命周期</h2>
<ul class="log" id="log" aria-live="polite">
<li>等待元素连接…</li>
</ul>
<p>连接、断开、属性变化各有回调,回调里不要做重活。</p>
</section>
<section id="rules">
<h2>4. 规则</h2>
<ul>
<li>名字必须包含短横线,且不能是保留名。</li>
<li>一个名字只能定义一次,重复定义会抛错。</li>
<li>不要在构造函数里读属性、加子节点或发请求。</li>
<li>属性变化用 <code>observedAttributes</code> 监听。</li>
<li>内部结构优先跟随语义与可访问性。</li>
<li>不用自定义元素替代原生按钮、链接与表单控件。</li>
</ul>
</section>
</main>
<footer>
<p>示例数据为虚构,仅用于教学。</p>
</footer>
</div>
<template id="user-card-tpl">
<article>
<h3 data-name></h3>
<p data-role></p>
</article>
</template>
<script>
class UserCard extends HTMLElement {
static observedAttributes = ["name", "role"];
connectedCallback() {
this.render();
}
attributeChangedCallback() {
if (this.isConnected) this.render();
}
render() {
const tpl = document.getElementById("user-card-tpl");
const node = tpl.content.cloneNode(true);
node.querySelector("[data-name]").textContent = this.getAttribute("name") ?? "未命名";
node.querySelector("[data-role]").textContent = this.getAttribute("role") ?? "读者";
this.replaceChildren(node);
}
}
customElements.define("user-card", UserCard);
class XMeter extends HTMLElement {
static observedAttributes = ["value", "label"];
connectedCallback() {
this.render();
}
attributeChangedCallback() {
if (this.isConnected) this.render();
}
render() {
const value = Math.max(0, Math.min(100, Number(this.getAttribute("value")) || 0));
const label = this.getAttribute("label") ?? "进度";
this.replaceChildren();
const wrap = document.createElement("div");
const head = document.createElement("div");
head.className = "label";
const name = document.createElement("span");
name.textContent = label;
const now = document.createElement("span");
now.textContent = value + "%";
head.append(name, now);
const track = document.createElement("div");
track.className = "track";
track.setAttribute("role", "progressbar");
track.setAttribute("aria-label", label);
track.setAttribute("aria-valuemin", "0");
track.setAttribute("aria-valuemax", "100");
track.setAttribute("aria-valuenow", String(value));
const fill = document.createElement("div");
fill.className = "fill";
fill.style.width = value + "%";
track.append(fill);
wrap.append(head, track);
this.append(wrap);
}
}
customElements.define("x-meter", XMeter);
const log = document.getElementById("log");
const meter = document.querySelector("x-meter");
const addLog = (text) => {
const li = document.createElement("li");
li.textContent = text;
log.append(li);
};
log.replaceChildren();
addLog("x-meter 已连接");
addLog("value=" + meter.getAttribute("value"));
document.getElementById("bump").addEventListener("click", () => {
const next = Math.min(100, Number(meter.getAttribute("value")) + 10);
meter.setAttribute("value", String(next));
addLog("value 变为 " + next + ",attributeChangedCallback 触发");
});
</script>
</body>
</html>