iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0
佛心分享-IT 人自學之術

從基礎開始—web學習之路系列 第 16

從基礎建設web網頁-第八章 HTML 組合應用

  • 分享至 

  • xImage
  •  

Web Component 組合應用-幸運籤

1.HTML 層

<h1>點擊來抽籤</h1>
<x-fortune></x-fortune>

x-fortune:自訂元件(Custom Element),代表 HTML 只宣告**"我需要一個籤語元件"**,並不管它怎麼運作。

2.JavaScript 層

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 層處理隨機抽籤、事件監聽、狀態更新。

3. Shadow DOM 層

<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" 會被更新為新的籤語。


上一篇
從基礎建設web網頁-第七章 HTML 組合應用
下一篇
從基礎建設web網頁-基礎概念 HTTP/HTTPS
系列文
從基礎開始—web學習之路17
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言