示例工程 42-custom-elements
42-custom-elements/demo-01-define/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; }
hello-name { display: block; padding: 10px 12px; border-radius: 8px; background: #eff6ff; color: #1e3a8a; }
ol { margin: 8px 0 0; padding-left: 22px; color: #334155; font-size: 14px; }
code { padding: 1px 5px; border-radius: 4px; background: #f1f5f9; font-family: ui-monospace, monospace; }
</style>
</head>
<body>
<h1>定义与升级</h1>
<div class="box">
<h2>未定义时</h2>
<p>浏览器把未知标签当普通行内元素,内容照常显示,但没有行为。</p>
<hello-name name="Ada">(还没有升级)</hello-name>
</div>
<div class="box">
<h2>定义之后</h2>
<p><code>customElements.define("hello-name", HelloName)</code> 会让已存在的元素立即升级。</p>
<hello-name name="Ada"></hello-name>
</div>
<div class="box">
<h2>时间线</h2>
<ol id="log"></ol>
</div>
<script>
const log = document.getElementById("log");
const add = (text) => {
const li = document.createElement("li");
li.textContent = text;
log.append(li);
};
class HelloName extends HTMLElement {
static observedAttributes = ["name"];
connectedCallback() {
this.render();
add("connectedCallback:" + this.getAttribute("name"));
}
attributeChangedCallback(name, oldValue, newValue) {
add("attributeChangedCallback:" + name + " " + oldValue + " → " + newValue);
if (this.isConnected) this.render();
}
render() {
this.textContent = "你好," + (this.getAttribute("name") ?? "访客");
}
}
add("定义前 customElements.get: " + Boolean(customElements.get("hello-name")));
customElements.define("hello-name", HelloName);
add("定义后 customElements.get: " + Boolean(customElements.get("hello-name")));
const second = document.querySelectorAll("hello-name")[1];
second.setAttribute("name", "Grace");
</script>
</body>
</html>