建立浮動式通知

浮動式通知是暫時性的狀態訊息,與選單不同的是,當使用者與頁面的其他部分互動時,不應關閉這些元素。popover="manual" 狀態不具備「輕觸關閉」行為,且允許多個通知並存,因此最適合用於這類通知。

導入指南

  • 必要:使用 popover="manual",讓通知持續顯示,直到明確關閉或指令碼逾時。
  • 建議使用容器管理多個浮動式訊息的堆疊。由於頂層的彈出式視窗會忽略父項 z-index,因此您必須個別定位,或在共同版面配置群組中定位。
  • 建議使用 sibling-index() 在浮動式通知之間加入邊界,讓堆疊中較低的項目也能顯示。
  • 務必使用 popovertargetaction="hide",在浮動式訊息中提供明確的「關閉」按鈕。
  • 建議使用 JavaScript 設定自動關閉計時器 (例如在 3000 毫秒後呼叫 hidePopover())。
  • 建議使用 transition-behavior: allow-discrete,為頂層的進入和退出動作加上動畫效果。

備用策略

Popover 的備用方案和瀏覽器支援

Popover API 主要是漸進增強,但其定義行為 (頂層升級、輕觸關閉和 popovertarget 叫用) 沒有僅限 CSS 的對等項目。舊版瀏覽器需要 polyfill,如果不想提供,則需要手動備用方案。

Polyfill:如要在舊版瀏覽器中支援 popover 屬性,請視情況載入 @oddbird/popover-polyfill。必要:檢查 HTMLElement.prototype 上的 popover 屬性,偵測功能,並僅在缺少原生支援時載入 polyfill,請勿無條件載入。

使用套件組合器或匯入對應:

// MANDATORY: Feature detect 'popover' on HTMLElement.prototype.
if (!("popover" in HTMLElement.prototype)) {
  import("@oddbird/popover-polyfill");
}

如果沒有繫結器,請從 <script type="module"> 內的 CDN 匯入:

<script type="module">
  if (!("popover" in HTMLElement.prototype)) {
    import("https://unpkg.com/@oddbird/popover-polyfill@latest/dist/popover.min.js");
  }
</script>

樣式注意事項:Polyfill 無法定義實際的 :popover-open 虛擬類別,因此會改為套用 .\:popover-open 類別。必要:請使用 :is() 或 :where() 結合兩者,否則不支援 :popover-open 的瀏覽器會捨棄整個規則:

[popover]:is(:popover-open, .\:popover-open) {
  display: block;
}

或者,如要使用不含 polyfill 的舊版備用方案,請使用 position: fixed,並透過 getBoundingClientRect() 手動計算座標,或在用途允許的情況下,使用 inset: auto 預設定位。

sibling-index()

  • 指南:如果瀏覽器不支援 sibling-index(),請使用 + 運算子手動新增邊界。例如:popover + popover { margin-top: 1rem }

anchor-positioning

  • 指南:使用 CSS 錨定位置 Polyfill。如要使用非 Polyfill 備用方案,請使用 @supports not (anchor-name: --foo) 將工具提示預設為可視區域底部的固定位置。

transition-behavior

  • 指引:如果系統不支援 transition-behavior,請使用 JavaScript 透過類別新增動畫,在浮動式訊息元素進出時顯示。