导航

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 将两者关联起来,按钮无需命名即可作为锚点。如果弹出层会超出视口,它就会翻转到按钮的另一侧。

类名位置
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 已支持通过 interestfor 在悬停或聚焦时触发预览。在其他浏览器中,链接仍可正常使用,预览不会显示。

#无障碍

  • 按钮的 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;    }  }}