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

如何在图片全屏div可见时阻止Bootstrap模态框按ESC键关闭

解决方案

核心原因是你绑定在图片div上的keydown事件触发后没有阻止冒泡,事件会向上传递到Bootstrap模态框的事件监听层,同时触发模态框的ESC关闭逻辑。通过阻止事件冒泡+临时修改模态框配置的双保险方案可以解决该问题,原生JS实现如下:


前置准备

给你的全屏图片div添加tabindex="-1"属性,确保div可以获得焦点,绑定的keydown事件才能正常触发:

<div id="fullscreenImageWrapper" class="d-none" tabindex="-1">
  <!-- 你的图片内容 -->
</div>

假设你使用的Bootstrap模态框id为detailModal,全屏图片div id为fullscreenImageWrapper。


代码实现

1. 打开全屏图片时临时禁用模态框ESC关闭

在你点击图片触发全屏显示的逻辑中加入配置修改代码:

function openFullscreenImage() {
  const imgWrapper = document.getElementById('fullscreenImageWrapper');
  const modalEl = document.getElementById('detailModal');
  // 显示全屏图片容器
  imgWrapper.classList.remove('d-none');
  // 聚焦容器保证键盘事件生效
  imgWrapper.focus();

  // 获取当前模态框实例
  const modalInstance = bootstrap.Modal.getInstance(modalEl);
  if (modalInstance) {
    // 保存模态框原有的ESC关闭配置,后续恢复用
    modalInstance._originalKeyboard = modalInstance._config.keyboard;
    // 临时禁用模态框ESC关闭
    modalInstance._config.keyboard = false;
  }
}

2. 绑定图片容器的ESC关闭逻辑,阻止事件冒泡

const imgWrapper = document.getElementById('fullscreenImageWrapper');
imgWrapper.addEventListener('keydown', function(e) {
  // 匹配ESC键
  if (e.key === 'Escape' || e.keyCode === 27) {
    // 阻止事件冒泡,避免触发上层模态框的监听逻辑
    e.stopPropagation();
    e.preventDefault();

    // 隐藏全屏图片容器
    this.classList.add('d-none');

    // 恢复模态框的原有ESC关闭配置
    const modalEl = document.getElementById('detailModal');
    const modalInstance = bootstrap.Modal.getInstance(modalEl);
    if (modalInstance && modalInstance._originalKeyboard !== undefined) {
      modalInstance._config.keyboard = modalInstance._originalKeyboard;
      delete modalInstance._originalKeyboard;
    }
  }
});

补充说明

  • 如果你还有点击图片容器外部、点击关闭按钮等其他关闭全屏图片的逻辑,需要在这些逻辑中同样加入恢复模态框keyboard配置的代码,避免后续ESC无法正常关闭模态框。
  • 该实现兼容Bootstrap 4和Bootstrap 5,不需要额外依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:18:03