YL

MODERN CSS

原生弹层Popover API

给元素加 popover 属性 + 一个按钮配 popovertarget,就得到一个自动支持顶层渲染、点击外部关闭、Esc 关闭的浮层。零 JS。

效果预览

筛选 ▾
按状态筛选
◉全部
○已付费
○试用中

适合用在哪

下拉菜单、筛选面板、提示卡、简易工具菜单。不适合需要焦点锁定的模态(那种用 dialog)。

容易踩的坑

  • 用 popover 做需要阻断操作的确认框,背景仍可交互,用户可能绕过确认。
  • 打开时焦点不进入浮层,键盘用户要多次 Tab 才能到达菜单项。
  • 入场动画不配 @starting-style,弹层首次打开时没有任何过渡。

设计提示词 · Prompt

原生弹层(Popover API):写 <button popovertarget="menu">筛选</button> 与 <div id="menu" popover>…</div>。浏览器自动处理:点击按钮开关、点击外部关闭、Esc 关闭、渲染到 top layer(不受父级 overflow:hidden 与 z-index 影响,这是相比手动实现最大的优势)。类型有三:popover="auto"(默认,自动关其他)、"manual"(不自动关)、"hint"(轻量提示,不打断)。用 ::backdrop 设置背后的遮罩。用 :popover-open 伪类做打开态样式。JS 侧还可调用 showPopover() / hidePopover() 与监听 toggle 事件。
Popover API: write <button popovertarget="menu">Filter</button> and <div id="menu" popover>…</div>. The browser handles automatically: toggling via the button, closing on outside click, closing on Esc, and rendering in the top layer (unaffected by a parent's overflow:hidden and z-index — the biggest advantage over a manual implementation). There are three types: popover="auto" (default; closes others automatically), "manual" (doesn't auto-close), and "hint" (lightweight hint, non-interrupting). Use ::backdrop to style the backdrop behind it, and the :popover-open pseudo-class for open-state styles. On the JS side you can also call showPopover() / hidePopover() and listen for the toggle event.

常见搭配

同一页面里经常和「原生弹层」一起出现的模式,可以收藏后用「组合收藏为整页提示词」一起交给 AI。

演示 HTML 结构

<div class="s" style="width:100%">
  <div class="mc-pop">
    <span class="mc-anchor__btn">筛选 ▾</span>
    <div class="mc-pop__card">
      <b>按状态筛选</b>
      <div class="mc-pop__row"><i>◉</i>全部</div>
      <div class="mc-pop__row"><i>○</i>已付费</div>
      <div class="mc-pop__row"><i>○</i>试用中</div>
    </div>
  </div>
</div>

标签