YL

MODERN CSS

原生弹窗<dialog> Element

<dialog> + .showModal() 一行得到一个真模态:自动焦点锁定、自动遮罩、自动 Esc 关闭、自动惰化背景。

效果预览

确认发布?

发布后所有访客立即可见,但可以随时回滚到上一版本。

取消发布

适合用在哪

确认对话框、表单模态、图片查看器。替代手写的 div + 遮罩 + 焦点管理方案。

容易踩的坑

  • 关闭时只隐藏 CSS 而不调用 close(),背景仍处于惰化状态,页面无法点击。
  • 长表单弹窗不设 max-height 与内部滚动,小屏上底部按钮被推出视口。
  • Esc 关闭时未拦截 cancel 事件,填写到一半的表单内容直接丢失。

设计提示词 · Prompt

原生弹窗(<dialog>):<dialog> 元素调用 .showModal() 打开(模态,带焦点锁定与背景惰化),.show() 则是非模态。浏览器自动提供:top layer 渲染、::backdrop 遮罩(可用 background: rgba(0,0,0,.42) 定制)、Esc 关闭(触发 cancel 事件,可 preventDefault 阻止)、焦点自动进入第一个可聚焦元素并在关闭后还原。返回值为 close 时可通过 dialog.returnValue 拿到返回值。要点:① 用 form method="dialog" 让内部按钮天然能关闭并回传值;② 关闭要用 .close(),别只切 CSS 类;③ 默认样式较差,需要自己重置 padding、border、圆角与最大宽度;④ 背景惰化是它相比手写方案最大的优势。
<dialog> Element: call .showModal() on a <dialog> to open it (modal, with focus trapping and background inerting); .show() opens it non-modally. The browser provides automatically: top-layer rendering, a ::backdrop overlay (customizable with background: rgba(0,0,0,.42)), Esc to close (fires a cancel event, which preventDefault can block), and focus moving to the first focusable element and being restored on close. When closed, the return value is available via dialog.returnValue. Key points: 1) use form method="dialog" so inner buttons naturally close it and pass back a value; 2) close with .close(), not just by toggling a CSS class; 3) the default styling is poor, so reset padding, border, radius, and max width yourself; 4) background inerting is its biggest advantage over hand-rolled solutions.

常见搭配

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

演示 HTML 结构

<div class="s" style="width:100%">
  <div class="mc-dlg">
    <div class="mc-dlg__b">
      <b>确认发布?</b>
      <p>发布后所有访客立即可见,但可以随时回滚到上一版本。</p>
      <div class="mc-dlg__f"><i>取消</i><i class="is-p">发布</i></div>
    </div>
  </div>
</div>

标签