You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fancybox5与浏览器返回按钮的多场景问题咨询

Fancybox 5 浏览器返回按钮交互优化方案

问题梳理

  • 默认配置下,打开Fancybox图片弹窗后点击浏览器返回按钮(或移动端滑动返回),会直接跳转到浏览器历史上一页,而非关闭弹窗停留在当前页面。
  • 使用内置hash插件+data-slug的方案虽能实现返回关闭弹窗,但每次打开图片都会新增一条历史记录,导致多次打开后需多次点击返回才能离开当前页面,不符合预期交互逻辑。

解决方案

通过自定义配置禁用默认历史记录新增逻辑,同时监听返回事件实现弹窗关闭,确保一次返回即可回到上一页面:

配置代码

Fancybox.defaults.backdropClick = "close";
Fancybox.bind("[data-fancybox]", {
  backdropClick: "close",
  idle: false,
  compact: false,
  history: false, // 禁用默认历史记录添加
  on: {
    init: (fancybox) => {
      // 监听popstate事件处理返回按钮
      const handlePopstate = () => {
        if (fancybox.isOpen) {
          fancybox.close();
          // 替换当前历史状态,避免重复触发
          history.replaceState(null, document.title, window.location.pathname + window.location.search);
        }
      };

      window.addEventListener("popstate", handlePopstate);

      // 弹窗关闭时移除监听
      fancybox.on("destroy", () => {
        window.removeEventListener("popstate", handlePopstate);
      });
    },
    open: (fancybox) => {
      // 打开弹窗时添加一条空的历史状态,确保返回时触发popstate
      history.pushState(null, document.title, window.location.href);
    },
  },
});

逻辑说明

  1. 关闭Fancybox默认的history功能,避免自动新增历史记录。
  2. 弹窗打开时手动添加一条历史状态,这样点击返回按钮会触发popstate事件。
  3. 监听popstate事件,当弹窗处于打开状态时关闭弹窗,并替换当前历史状态,确保后续返回直接跳转到上一页面。
  4. 弹窗销毁时移除事件监听,避免内存泄漏。

这样配置后,无论打开多少次图片弹窗,关闭后点击一次返回按钮就能直接回到浏览器历史的上一页,同时点击返回按钮会优先关闭当前弹窗。

内容的提问来源于stack exchange,提问作者Mitrovic Srdjan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 23:53:25