最後活躍 10 months ago

這段 HTML 結合 Lit(透過 CDN 載入),建立了一個自訂 Web 元件 <simple-greeting>,用於 顯示問候語。該元件支援 name 屬性,可動態變更顯示的名稱,並透過 LitElement 定義樣式與繪製邏輯。這適用於 前端 UI 元件開發、動態內容繪製,並展示了如何使用 Web Components 來構建 可重用、獨立且輕量的前端元件。

修訂 9efcf8b489883a5363211bbe441c850af7bec29f

lit_cdn_example.html 原始檔案
1<!DOCTYPE html>
2<html lang="zh-TW">
3<head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>Lit CDN Example</title>
7</head>
8<body>
9 <!-- 自定義元件 -->
10 <simple-greeting name="Lit"></simple-greeting>
11
12 <script type="module">
13 // 從 CDN 導入 Lit
14 import { LitElement, html, css } from "https://cdn.jsdelivr.net/npm/lit@2.6.1/+esm";
15
16 // 定義 SimpleGreeting 元件
17 class SimpleGreeting extends LitElement {
18 static properties = {
19 name: { type: String }, // 定義 name 屬性
20 };
21
22 constructor() {
23 super();
24 this.name = 'World'; // 預設屬性值
25 }
26
27 // 定義樣式
28 static styles = css`
29 p {
30 color: blue;
31 font-size: 20px;
32 font-family: Arial, sans-serif;
33 }
34 `;
35
36 // 定義模板
37 render() {
38 return html`<p>Hello, ${this.name}!</p>`;
39 }
40 }
41
42 // 註冊自定義元素
43 customElements.define('simple-greeting', SimpleGreeting);
44 </script>
45</body>
46</html>
47