<h1>點擊來抽籤</h1>
<x-fortune></x-fortune>
x-fortune:自訂元件(Custom Element),代表 HTML 只宣告**"我需要一個籤語元件"**,並不管它怎麼運作。
class XFortune extends HTMLElement {
constructor() {
super();
this.attachShadow({mode:'open'});
}
connectedCallback() { this.render(); }
get fortunes() { return ["大吉", "中吉", "末吉", "大凶", "小兇"]; }
pickFortune() {
const i = Math.floor(Math.random() * this.fortunes.length);
return this.fortunes[i];
}
render() { ... }
}
customElements.define("x-fortune", XFortune);
我們這邊定義一個 XFortune 類別,繼承 HTMLElement,然後在 connectedCallback() 初始化並渲染元件。
pickFortune() 方法:隨機挑選籤語。
customElements.define("x-fortune", XFortune):註冊元件,讓 HTML 可以用 x-fortune。
這邊要注意 JavaScript 層處理隨機抽籤、事件監聽、狀態更新。
<style>
button {
padding: 10px 20px;
border: none;
background: orange;
color: white;
font-size: 1.2rem;
cursor: pointer;
}
p {
margin-top: 1rem;
font-weight: bold;
color: purple;
}
</style>
<button>抽一支籤</button>
<p id="msg">等待你的籤語...</p>
button 樣式:
padding: 10px 20px 的意思是讓按鈕有內邊距,看起來才不會擠在一起。
border: none 是移除瀏覽器預設的邊框。
font-size: 1.2rem 字體稍微放大。
cursor: pointer; → 滑鼠移上去時顯示手指游標,提示可點擊。
p 樣式:
margin-top: 1rem 與按鈕保持間距。
font-weight: bold 可以讓文字加粗。
透過 this.attachShadow({mode:'open'}) 建立 Shadow DOM。
事件:按下 button 後,p id="msg" 會被更新為新的籤語。