创建消息框通知

消息框通知是暂时性状态消息。与菜单不同,当用户与页面的其他部分互动时,它们不应关闭。popover="manual" 状态非常理想,因为它没有“轻触关闭”行为,并且允许多个通知共存。

实现准则

  • 强制要求:使用 popover="manual",以便通知保持可见,直到被脚本明确关闭或超时。
  • 请使用容器来管理多个消息框的堆叠。由于顶层中的弹出式窗口会忽略父级 z-index,因此您必须单独定位它们,或将它们放在一个通用布局组中。
  • 务必使用 sibling-index() 在消息提示通知之间添加外边距,以便堆叠中位置较低的内容可见。
  • 务必在消息框内提供一个明确的“关闭”按钮,并使用 popovertargetaction="hide"。
  • 务必使用 JavaScript 实现自动关闭计时器(例如,在 3000 毫秒后调用 hidePopover())。
  • 建议利用 transition-behavior: allow-discrete 为顶层的进入和退出添加动画效果。

后备策略

Popover 的回退和浏览器支持

Popover API 主要是一种渐进增强技术,但其核心行为(顶层提升、轻触关闭和 popovertarget 调用)没有仅限 CSS 的等效项。旧版浏览器需要 polyfill,如果您不想提供 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 通过类添加动画,以便在消息提示框元素进入和退出时显示动画。