網站導覽

v2.1.0
覆疊元件

彈出面板

錨定在開啟按鈕旁的彈出面板。

本頁內容

彈出面板依附於開啟它的按鈕。在任一元素加上 popover 屬性和 .popover,再用 popovertarget 讓按鈕指向該元素。瀏覽器會將面板移到頂層,點擊面板外部或按下 Esc 時關閉,並讓面板在 Tab 順序中緊接在按鈕之後。面板由 CSS 錨點定位,不需要用腳本定位。

彈出面板

<button type="button" class="btn" popovertarget="share">Share</button><div id="share" popover class="popover">  <div class="flex flex-col gap-sm w(260)">    <p class="m(0) fg-text-strong">Share this project</p>    <div class="input-group input-group-sm">      <input class="input-group-field" value="https://atlas.dev/p/9f2c" readonly aria-label="Link">      <button type="button" class="btn">Copy</button>    </div>  </div></div>
<>  <button type="button" className="btn" popoverTarget="share">Share</button>  <div id="share" popover="" className="popover">    <div className="flex flex-col gap-sm w(260)">      <p className="m(0) fg-text-strong">Share this project</p>      <div className="input-group input-group-sm">        <input className="input-group-field" defaultValue="https://atlas.dev/p/9f2c" readOnly aria-label="Link" />        <button type="button" className="btn">Copy</button>      </div>    </div>  </div></>
<button type="button" class="btn" popovertarget="share">Share</button><div id="share" popover class="popover">  <div class="flex flex-col gap-sm w(260)">    <p class="m(0) fg-text-strong">Share this project</p>    <div class="input-group input-group-sm">      <input class="input-group-field" value="https://atlas.dev/p/9f2c" readonly aria-label="Link">      <button type="button" class="btn">Copy</button>    </div>  </div></div>
<template>  <button type="button" class="btn" popovertarget="share">Share</button>  <div id="share" popover class="popover">    <div class="flex flex-col gap-sm w(260)">      <p class="m(0) fg-text-strong">Share this project</p>      <div class="input-group input-group-sm">        <input class="input-group-field" value="https://atlas.dev/p/9f2c" readonly aria-label="Link">        <button type="button" class="btn">Copy</button>      </div>    </div>  </div></template>

#放置位置

彈出面板會在按鈕下方 6px 處開啟,並與按鈕的起始邊緣對齊。Popover API 會將按鈕與面板連結,因此無須另外指定 CSS 錨點名稱。面板若會超出檢視區,就會翻到另一側。

類別放置位置
popover位於下方,與起始邊緣對齊
popover-end與結束邊緣對齊,適合放在一列末端的按鈕
popover-center相對於按鈕置中
popover-top位於按鈕上方,可搭配 popover-end 或 popover-center

放置位置

<button type="button" class="btn" popovertarget="place-start">Start</button><button type="button" class="btn" popovertarget="place-center">Center</button><button type="button" class="btn" popovertarget="place-end">End</button><button type="button" class="btn" popovertarget="place-top">Top</button><div id="place-start" popover class="popover">Lined up with the start edge.</div><div id="place-center" popover class="popover popover-center">Centered on the button.</div><div id="place-end" popover class="popover popover-end">Lined up with the end edge.</div><div id="place-top" popover class="popover popover-top popover-center">Above the button.</div>
<>  <button type="button" className="btn" popoverTarget="place-start">Start</button>  <button type="button" className="btn" popoverTarget="place-center">Center</button>  <button type="button" className="btn" popoverTarget="place-end">End</button>  <button type="button" className="btn" popoverTarget="place-top">Top</button>  <div id="place-start" popover="" className="popover">Lined up with the start edge.</div>  <div id="place-center" popover="" className="popover popover-center">Centered on the button.</div>  <div id="place-end" popover="" className="popover popover-end">Lined up with the end edge.</div>  <div id="place-top" popover="" className="popover popover-top popover-center">    Above the button.  </div></>
<button type="button" class="btn" popovertarget="place-start">Start</button><button type="button" class="btn" popovertarget="place-center">Center</button><button type="button" class="btn" popovertarget="place-end">End</button><button type="button" class="btn" popovertarget="place-top">Top</button><div id="place-start" popover class="popover">Lined up with the start edge.</div><div id="place-center" popover class="popover popover-center">Centered on the button.</div><div id="place-end" popover class="popover popover-end">Lined up with the end edge.</div><div id="place-top" popover class="popover popover-top popover-center">Above the button.</div>
<template>  <button type="button" class="btn" popovertarget="place-start">Start</button>  <button type="button" class="btn" popovertarget="place-center">Center</button>  <button type="button" class="btn" popovertarget="place-end">End</button>  <button type="button" class="btn" popovertarget="place-top">Top</button>  <div id="place-start" popover class="popover">Lined up with the start edge.</div>  <div id="place-center" popover class="popover popover-center">Centered on the button.</div>  <div id="place-end" popover class="popover popover-end">Lined up with the end edge.</div>  <div id="place-top" popover class="popover popover-top popover-center">Above the button.</div></template>

瀏覽器若不支援錨點定位,彈出面板仍可正常開關,並會依照瀏覽器對彈出面板的預設定位顯示在檢視區中央。

#搭配表單

彈出面板可以容納控制項。面板開啟時,焦點會留在按鈕上。按 Tab 可將焦點移入面板,也可在第一個欄位加上 autofocus,讓焦點在開啟時直接移到該欄位。

搭配表單

<button type="button" class="btn" popovertarget="rename">Rename</button><form id="rename" popover class="popover">  <div class="flex flex-col gap-sm w(240)">    <label class="field">Project name <input class="input input-sm" value="atlas" autofocus></label>    <div class="flex justify-end gap-xs">      <button type="button" class="btn btn-sm" popovertarget="rename" popovertargetaction="hide">        Cancel      </button>      <button type="button" class="btn btn-sm btn-primary" popovertarget="rename" popovertargetaction="hide">        Save      </button>    </div>  </div></form>
<>  <button type="button" className="btn" popoverTarget="rename">Rename</button>  <form id="rename" popover="" className="popover">    <div className="flex flex-col gap-sm w(240)">      <label className="field">        Project name <input className="input input-sm" defaultValue="atlas" autoFocus />      </label>      <div className="flex justify-end gap-xs">        <button type="button" className="btn btn-sm" popoverTarget="rename" popoverTargetAction="hide">          Cancel        </button>        <button type="button" className="btn btn-sm btn-primary" popoverTarget="rename" popoverTargetAction="hide">          Save        </button>      </div>    </div>  </form></>
<button type="button" class="btn" popovertarget="rename">Rename</button><form id="rename" popover class="popover">  <div class="flex flex-col gap-sm w(240)">    <label class="field">Project name <input class="input input-sm" value="atlas" autofocus></label>    <div class="flex justify-end gap-xs">      <button type="button" class="btn btn-sm" popovertarget="rename" popovertargetaction="hide">        Cancel      </button>      <button type="button" class="btn btn-sm btn-primary" popovertarget="rename" popovertargetaction="hide">        Save      </button>    </div>  </div></form>
<template>  <button type="button" class="btn" popovertarget="rename">Rename</button>  <form id="rename" popover class="popover">    <div class="flex flex-col gap-sm w(240)">      <label class="field">        Project name <input class="input input-sm" value="atlas" autofocus>      </label>      <div class="flex justify-end gap-xs">        <button type="button" class="btn btn-sm" popovertarget="rename" popovertargetaction="hide">          Cancel        </button>        <button type="button" class="btn btn-sm btn-primary" popovertarget="rename" popovertargetaction="hide">          Save        </button>      </div>    </div>  </form></template>

#指標懸停時

指標停在連結或按鈕上,或連結或按鈕取得焦點時,也可開啟彈出面板來預覽其指向的內容。為面板加上 popover="hint",再用 interestfor 讓觸發元素指向面板。提示面板不會關閉已開啟的選單或其他彈出面板。請只放預覽內容,因為觸控螢幕的使用者只能透過長按查看。任何資訊都不應只在這裡提供。

指標懸停時

<p class="m(0) text-sm fg-text-body">  Deployed by <a class="link" href="#ada" interestfor="ada-card">Ada Lovelace</a> two hours ago.</p><div id="ada-card" popover="hint" class="popover">  <div class="flex items-center gap-sm">    <span class="avatar avatar-lg"><img class="avatar-image" src="/demo/portrait-1.svg" alt></span>    <div class="flex flex-col">      <span class="fg-text-strong">Ada Lovelace</span>      <span class="text-xs fg-text-muted">Owner · 412 deployments</span>    </div>  </div></div>
<>  <p className="m(0) text-sm fg-text-body">    Deployed by <a className="link" href="#ada" {...{ interestfor: 'ada-card' }}>Ada Lovelace</a> two hours ago.  </p>  <div id="ada-card" popover="hint" className="popover">    <div className="flex items-center gap-sm">      <span className="avatar avatar-lg">        <img className="avatar-image" src="/demo/portrait-1.svg" alt="" />      </span>      <div className="flex flex-col">        <span className="fg-text-strong">Ada Lovelace</span>        <span className="text-xs fg-text-muted">Owner · 412 deployments</span>      </div>    </div>  </div></>
<p class="m(0) text-sm fg-text-body">  Deployed by <a class="link" href="#ada" interestfor="ada-card">Ada Lovelace</a> two hours ago.</p><div id="ada-card" popover="hint" class="popover">  <div class="flex items-center gap-sm">    <span class="avatar avatar-lg"><img class="avatar-image" src="/demo/portrait-1.svg" alt></span>    <div class="flex flex-col">      <span class="fg-text-strong">Ada Lovelace</span>      <span class="text-xs fg-text-muted">Owner · 412 deployments</span>    </div>  </div></div>
<template>  <p class="m(0) text-sm fg-text-body">    Deployed by <a class="link" href="#ada" interestfor="ada-card">Ada Lovelace</a> two hours ago.  </p>  <div id="ada-card" popover="hint" class="popover">    <div class="flex items-center gap-sm">      <span class="avatar avatar-lg">        <img class="avatar-image" src="/demo/portrait-1.svg" alt>      </span>      <div class="flex flex-col">        <span class="fg-text-strong">Ada Lovelace</span>        <span class="text-xs fg-text-muted">Owner · 412 deployments</span>      </div>    </div>  </div></template>
將指標移到名稱上,或按 Tab 將焦點移到名稱。

Chrome 和 Edge 已支援這類預覽觸發元素。其他瀏覽器仍可正常開啟連結,但不會顯示預覽。

#無障礙

  • 瀏覽器會為按鈕設定 aria-expanded,請勿自行設定。
  • 彈出面板是非模態的,開啟時使用者仍可操作頁面。如果必須先完成或取消一項任務,請使用對話框。
  • 使用選單列出可執行的操作,使用工具提示顯示指標懸停時的標籤。

#React、Svelte 和 Vue

popover 元件會依應用程式狀態開關彈出面板,也會在瀏覽器開關面板時發出通知。觸發元素和內容仍由頁面自己的標記定義。它的 mode 可以是 auto、manual 或 hint:hint 是指標懸停時顯示的預覽,傳給觸發元素的屬性會是 interestfor 而不是 popovertarget,因此請將這些屬性展開套用到顯示預覽的連結或按鈕上。執行 npx master-ui add popover 即可將元件複製到專案中。請參閱 React、Svelte 和 Vue,了解元件的建構和使用方式。

若只有一個觸發元素指向彈出面板,受控開啟時會沿用按下該元素時的錨點。在自己的指令碼中,可用 popover.showPopover({ source: trigger }) 傳入觸發元素。有多個觸發元素時,請傳入實際開啟面板的元素。若在缺少 source 支援時也要依固定觸發元素定位,可分別將 details-trigger 與 details-popover 加到兩者上,並使用相同的錨點名稱。

app.css
.details-trigger { anchor-name: --details; }.details-popover { position-anchor: --details; }
ui/popover.tsx
'use client'import { useEffect, useId, useReducer, useRef, type ComponentProps, type ReactNode } from 'react'import { showFromPopoverTrigger } from '@master/ui/behaviors/internal.js'export interface PopoverProps extends Omit<ComponentProps<'div'>, 'popover' | 'ref'> {  /** Whether the popover is open, when this component is told. Leave it out and the trigger opens it. */  open?: boolean  onOpenChange?: (open: boolean) => void  /**   * The button that opens the popover: spread what it is given on a button of your own. In `hint` mode it   * is the link or the button that shows it on hover and on focus, and is given `interestfor`.   */  trigger?: (attributes: PopoverTriggerAttributes) => ReactNode  /**   * `auto` closes on a press outside and on Esc; `manual` stays until it is closed; `hint` is a preview the   * trigger shows while it is hovered or focused, and does not close another popover that is open.   */  mode?: 'auto' | 'manual' | 'hint'}/** What the trigger is given: `popoverTarget` to open the popover, or `interestfor` to show a hint. */export type PopoverTriggerAttributes = { popoverTarget: string } | { interestfor: string }/** * A popover. The browser opens it from the trigger, places it against the trigger and dismisses it; this * component only opens and closes it from `open`, and says when the browser did. */export function Popover({ open, onOpenChange, trigger, mode = 'auto', className, id, children, ...root }: PopoverProps) {  const generated = useId()  const name = id ?? generated  const element = useRef<HTMLDivElement>(null)  const heard = useRef(onOpenChange)  /** What the owner knows: the last state it set or was told. */  const known = useRef(false)  const [tick, again] = useReducer((count: number) => count + 1, 0)  useEffect(() => { heard.current = onOpenChange })  useEffect(() => {    const popover = element.current    if (!popover || open === undefined) return    const shown = popover.matches(':popover-open')    known.current = open    if (open && !shown) showFromPopoverTrigger(popover)    else if (!open && shown) popover.hidePopover()  }, [open, tick])  useEffect(() => {    const popover = element.current    if (!popover) return    const report = () => {      const shown = popover.matches(':popover-open')      if (shown !== known.current) heard.current?.(known.current = shown)      // An `open` this component is told wins: if its owner did not take the change, the popover goes back.      again()    }    popover.addEventListener('toggle', report)    return () => popover.removeEventListener('toggle', report)  }, [])  return (    <>      {trigger?.(mode === 'hint' ? { interestfor: name } : { popoverTarget: name })}      <div id={name} popover={mode} className={className ? `popover ${className}` : 'popover'} ref={element} {...root}>{children}</div>    </>  )}
ui/Popover.svelte
<script lang="ts" module>  import type { Snippet } from 'svelte'  import type { HTMLAttributes } from 'svelte/elements'  export interface PopoverProps extends Omit<HTMLAttributes<HTMLDivElement>, 'popover'> {    /** Whether the popover is open. Bind it, or leave it out and the trigger opens it. */    open?: boolean    onOpenChange?: (open: boolean) => void    /**     * The button that opens the popover: spread what it is given on a button of your own. In `hint` mode it     * is the link or the button that shows it on hover and on focus, and is given `interestfor`.     */    trigger?: Snippet<[PopoverTriggerAttributes]>    /**     * `auto` closes on a press outside and on Esc; `manual` stays until it is closed; `hint` is a preview the     * trigger shows while it is hovered or focused, and does not close another popover that is open.     */    mode?: 'auto' | 'manual' | 'hint'  }  /** What the trigger is given: `popovertarget` to open the popover, or `interestfor` to show a hint. */  export type PopoverTriggerAttributes = { popovertarget: string } | { interestfor: string }</script><script lang="ts">  import type { Attachment } from 'svelte/attachments'  import { showFromPopoverTrigger } from '@master/ui/behaviors/internal.js'  let { open = $bindable(), onOpenChange, trigger, mode = 'auto', class: className, id, children, ...root }: PopoverProps = $props()  const generated = $props.id()  const name = $derived(id ?? generated)  /** What the owner knows: the last state it set or was told. */  let known = false  const presence: Attachment<HTMLDivElement> = (popover) => {    const report = () => {      const shown = popover.matches(':popover-open')      if (shown === known) return      open = known = shown      onOpenChange?.(known)    }    popover.addEventListener('toggle', report)    $effect(() => {      if (open === undefined) return      const shown = popover.matches(':popover-open')      known = open      if (open && !shown) showFromPopoverTrigger(popover)      else if (!open && shown) popover.hidePopover()    })    return () => popover.removeEventListener('toggle', report)  }</script><!--  @component  A popover. The browser opens it from the trigger, places it against the trigger and dismisses it; this  component only opens and closes it from `open`, and says when the browser did.-->{@render trigger?.(mode === 'hint' ? { interestfor: name } : { popovertarget: name })}<div id={name} popover={mode} class={['popover', className]} {@attach presence} {...root}>{@render children?.()}</div>
ui/Popover.vue
<script setup lang="ts">import { computed, nextTick, onMounted, useId, useTemplateRef, watch } from 'vue'import { showFromPopoverTrigger } from '@master/ui/behaviors/internal.js'defineOptions({ inheritAttrs: false })const { id, mode = 'auto' } = defineProps<{  id?: string  /**   * `auto` closes on a press outside and on Esc; `manual` stays until it is closed; `hint` is a preview the   * trigger shows while it is hovered or focused, and does not close another popover that is open.   */  mode?: 'auto' | 'manual' | 'hint'}>()/** Whether the popover is open: `v-model:open`. Leave it out and the trigger opens it. */const open = defineModel<boolean>('open')defineSlots<{  /**   * The button that opens the popover: bind what it is given on a button of your own. In `hint` mode it is   * the link or the button that shows it on hover and on focus, and is given `interestfor`.   */  trigger?: (attributes: { popovertarget: string } | { interestfor: string }) => unknown  default?: () => unknown}>()/* * A popover. The browser opens it from the trigger, places it against the trigger and dismisses it; this * component only opens and closes it from `open`, and says when the browser did. */const generated = useId()const name = computed(() => id ?? generated)const triggerAttributes = computed(() => mode === 'hint' ? { interestfor: name.value } : { popovertarget: name.value })const root = useTemplateRef<HTMLDivElement>('root')/** What the owner knows: the last state it set or was told. */let known = falseconst sync = () => {  const popover = root.value  if (!popover || open.value === undefined) return  const shown = popover.matches(':popover-open')  known = open.value  if (open.value && !shown) showFromPopoverTrigger(popover)  else if (!open.value && shown) popover.hidePopover()}const report = () => {  const popover = root.value  if (!popover) return  const shown = popover.matches(':popover-open')  if (shown !== known) open.value = known = shown  // An `open` this component is told wins: if its owner did not take the change, the popover goes back.  void nextTick(sync)}onMounted(sync)watch(open, sync, { flush: 'post' })</script><template>  <slot name="trigger" v-bind="triggerAttributes" />  <div :id="name" :popover="mode" class="popover" ref="root" v-bind="$attrs" @toggle="report"><slot /></div></template>

#類別

類別說明
popover彈出面板須設在具有 popover 屬性的元素上才會顯示。面板在按鈕下方開啟,與按鈕的起始邊緣對齊,間距為 --anchored-gap(6px),碰到檢視區邊緣時會翻轉方向
popover-end與按鈕的末端邊緣對齊,適用於一列末端的按鈕。搭配 popover 使用
popover-center與按鈕置中對齊。搭配 popover 使用
popover-top在按鈕上方開啟,可搭配 popover-end 或 popover-center。搭配 popover 使用

#自訂屬性

屬性預設值說明
--popover-padding1rem面板的內距
--popover-max-width22rem文字開始換行前,面板可擴展到的最大寬度
--anchored-gap浮層與觸發控制項之間的間距,未設定時為 6px。設定於 popover

#原始碼

@master/ui/components/popover.css
/* * Popover: a floating sheet opened by a button with popovertarget (or commandfor and command="toggle-popover"). * The popover attribute supplies the top layer, light dismiss and Escape; CSS anchor positioning places the * sheet against its button and flips it at the viewport edge. Geometry: a 12px corner, the same as a menu's, * and 16px of padding. */@layer components.ui {  .popover {    --popover-padding: 1rem;    --popover-max-width: 22rem;    --surface-color: var(--color-surface-floating);    width: max-content;    max-width: min(var(--popover-max-width), calc(100vw - 1rem));    /* A long sheet scrolls inside the viewport, as a menu does, instead of running past its edge. */    max-height: calc(100dvh - 1rem);    padding: var(--popover-padding);    border: 0;    border-radius: calc(var(--radius-control-sm) * var(--corner-scale) + 4px);    corner-shape: var(--corner-shape);    overflow: auto;    background: var(--color-surface-floating);    color: var(--color-text-body);    box-shadow: var(--shadow-floating);    font-size: .875rem;    line-height: 1.5;    transform-origin: top;    @apply --anchored;    @apply --pop;    scrollbar-width: thin;    scrollbar-color: var(--color-line-strong) transparent;    overflow-wrap: anywhere;    overscroll-behavior: contain;    /* Line up with the button's end edge instead of its start. */    &.popover-end {      --anchored-inline: span-inline-start;    }    &.popover-center {      --anchored-inline: span-all;    }    /* Open above the button. */    &.popover-top {      --anchored-block: block-start;      transform-origin: bottom;    }    @media (forced-colors: active) {      outline: 1px solid CanvasText;      outline-offset: -1px;    }  }}