如何实现Bootstrap两个模态框(Modal)并排显示?
解决Bootstrap两个模态框并排显示的问题
嘿,我懂你现在的困扰——单个模态框跑起来顺得很,想搞两个并排就翻车了对吧?其实Bootstrap默认的模态框是按全屏居中设计的,自带的fixed定位和布局样式会和栅格系统“打架”,再加上你是用JS动态加载的模态框,得把样式调整和JS结构结合起来才行。下面给你一套可行的方案:
1. 先改模态框的核心样式
默认的.modal是position: fixed,会脱离栅格的布局流,所以我们得重写这个属性,让栅格能控制它的位置:
/* 自定义并排模态框的样式 */ .modal.side-by-side { position: absolute; /* 从fixed改成absolute,交给栅格管理位置 */ top: 50%; left: auto; /* 取消默认的左右定位 */ right: auto; transform: translateY(-50%); /* 只保留垂直居中,水平由栅格控制 */ max-width: 48%; /* 给两个模态框留点间距 */ margin: 0 1%; /* 可选:如果想让模态框高度固定,加个max-height和滚动 */ max-height: 80vh; overflow-y: auto; }
2. 用栅格结构包裹动态加载的模态框
因为你是用JS加载模态框,得确保每个模态框都放在Bootstrap的栅格列里,整体用容器和行包裹。这里给你一个JS示例:
// 封装创建模态框的函数 function buildModal(content, modalId) { const modalEl = document.createElement('div'); modalEl.className = 'modal side-by-side fade'; modalEl.id = modalId; modalEl.innerHTML = ` <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">${modalId}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> ${content} </div> </div> </div> `; return modalEl; } // 创建栅格容器和行,用来放两个模态框 const gridWrapper = document.createElement('div'); gridWrapper.className = 'container-fluid position-fixed top-0 start-0 w-100 h-100 d-flex align-items-center justify-content-center'; const row = document.createElement('div'); row.className = 'row w-100'; // 创建第一个模态框并放入col-6 const modal1 = buildModal('这是第一个模态框的内容', 'modal-1'); const col1 = document.createElement('div'); col1.className = 'col-6'; col1.appendChild(modal1); // 创建第二个模态框并放入col-6 const modal2 = buildModal('这是第二个模态框的内容', 'modal-2'); const col2 = document.createElement('div'); col2.className = 'col-6'; col2.appendChild(modal2); // 把列加到行里,行加到容器,最后塞到body里 row.append(col1, col2); gridWrapper.appendChild(row); document.body.appendChild(gridWrapper); // 初始化并显示两个模态框 const modalInst1 = new bootstrap.Modal(modal1); const modalInst2 = new bootstrap.Modal(modal2); modalInst1.show(); modalInst2.show();
3. 处理模态框的背景层
默认情况下,每个模态框都会生成一个.modal-backdrop,这样会出现两层背景,看起来很奇怪。我们可以手动添加一个全局背景,避免重复:
// 手动添加单个背景层 function addSingleBackdrop() { if (!document.querySelector('.modal-backdrop')) { const backdrop = document.createElement('div'); backdrop.className = 'modal-backdrop fade show'; document.body.appendChild(backdrop); // 点击背景关闭两个模态框并移除背景 backdrop.addEventListener('click', () => { modalInst1.hide(); modalInst2.hide(); backdrop.remove(); }); } } // 在显示模态框前调用这个函数 addSingleBackdrop();
关键注意点
- 一定要把模态框的
position从fixed改成absolute,不然栅格完全控制不了它的位置 - 栅格容器要设置成
position-fixed并占满整个视口,这样两个模态框能整体居中 - 如果是Bootstrap 4版本,把
data-bs-dismiss改成data-dismiss,模态框初始化用$(modalEl).modal('show')就行,核心逻辑不变
内容的提问来源于stack exchange,提问作者Den1al
相关产品推荐
相关产品推荐

