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

如何实现Bootstrap模态框加载自动打开、1分钟无操作自动关闭

Bootstrap 5模态框自动打开+定时关闭实现方案

你提供的代码使用了data-bs-dismiss属性,属于Bootstrap 5的语法,直接添加以下JavaScript代码即可实现需求:

// 等待DOM完全加载后执行
document.addEventListener('DOMContentLoaded', function() {
  // 获取模态框元素
  const modalEl = document.getElementById('overlay');
  // 初始化模态框实例
  const bsModal = new bootstrap.Modal(modalEl);
  // 页面加载自动打开模态框
  bsModal.show();

  // 设置1分钟(60000毫秒)后自动关闭的定时器
  const autoCloseTimer = setTimeout(() => {
    bsModal.hide();
  }, 60000);

  // 监听模态框关闭事件:用户手动关闭时清除定时器,避免无效执行
  modalEl.addEventListener('hidden.bs.modal', () => {
    clearTimeout(autoCloseTimer);
  });
});

代码说明

  • 定时器时长单位为毫秒,1分钟对应60000,如果需要调整时长直接修改该数值即可
  • 加了模态框关闭事件的监听逻辑,不管是用户手动点击关闭按钮,还是自动触发关闭,都会清除残留的定时器,不会出现定时器到点后报错的问题
  • 如果你使用的是带jQuery的Bootstrap版本(Bootstrap 3/4也适用),可以用更简化的写法:
$(function() {
  // 自动打开模态框
  $('#overlay').modal('show');
  // 设置定时关闭
  const timer = setTimeout(() => {
    $('#overlay').modal('hide');
  }, 60000);
  // 关闭时清除定时器
  $('#overlay').on('hidden.bs.modal', () => {
    clearTimeout(timer);
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 09:24:03