Bootstrap4 模态框
核对 Bootstrap 4 模态框(Modal)的层级结构、触发与关闭交互、背景遮罩与滚动锁定,以及 `.modal-sm` 与 `.modal-lg` 尺寸变体。
学完这一章,你能够
- 核对 Bootstrap 4 模态框(Modal)的层级结构、触发与关闭交互、背景遮罩与滚动锁定,以及 `.modal-sm` 与 `.modal-lg` 尺寸变体。
模态框结构与打开/关闭生命周期
模态框(Modal)是覆盖在当前父页面之上的对话框浮层,适合在不跳转页面的前提下展示详情、确认操作或承载子表单。触发按钮声明 `data-toggle="modal"` 与 `data-target="#myModal"`,模态框根元素采用 `<div class="modal fade" id="myModal">`,内部依次嵌套 `.modal-dialog`、`.modal-content` 及头部 `.modal-header`(含 `.modal-title` 与 `data-dismiss="modal"` 关闭按钮)、主体 `.modal-body`、底部 `.modal-footer`。本站离线 Chromium 实测:初始模态框 `display: none` 且无遮罩;点击触发按钮后模态框切换为 `display: block`(`z-index: 1050`)、`body` 附加 `.modal-open` 锁定滚动(`overflow: hidden`)并生成 1 层 `.modal-backdrop`;无论点击头部 `×`、底部关闭按钮、按 `Escape` 键还是点击对话框外侧遮罩区,模态框均恢复 `display: none` 并同步移除遮罩与 `.modal-open`。
模态框尺寸变体
调节对话框宽度时应把尺寸修饰类添加到 `.modal-dialog` 元素上(而非最外层 `.modal`):`.modal-sm` 用于紧凑型小模态框,`.modal-lg` 用于宽内容大模态框。本站离线 Chromium 在 `1200px` 桌面视口下实测三档渲染宽度精确对应:小模态框 `300px`、默认模态框 `500px`、大模态框 `800px`。
离线 Chromium 实测模态框开关生命周期、遮罩/ESC 关闭及 sm/默认/lg 三档宽度
"""Offline Playwright Chromium lab for Bootstrap 4 Chapter 28 (modal)."""
import json
from playwright.sync_api import sync_playwright
BS4_MODAL_CSS = """
* { box-sizing: border-box; }
body { margin: 16px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; font-size: 16px; }
body.modal-open { overflow: hidden; }
.modal {
position: fixed; top: 0; left: 0; z-index: 1050; display: none;
width: 100%; height: 100%; overflow: hidden; outline: 0;
}
.modal.show { display: block; }
.modal-dialog { position: relative; width: auto; margin: 1.75rem auto; max-width: 500px; pointer-events: none; }
@media (min-width: 576px) {
.modal-dialog { max-width: 500px; }
.modal-sm { max-width: 300px; }
}
@media (min-width: 992px) {
.modal-lg { max-width: 800px; }
}
.modal-content {
position: relative; display: flex; flex-direction: column; width: 100%;
pointer-events: auto; background-color: #fff; border: 1px solid rgba(0,0,0,.2); border-radius: 0.3rem;
}
.modal-header { display: flex; align-items: flex-start; justify-content: space-between; padding: 1rem; border-bottom: 1px solid #dee2e6; }
.modal-body { position: relative; flex: 1 1 auto; padding: 1rem; }
.modal-footer { display: flex; align-items: center; justify-content: flex-end; padding: 0.75rem; border-top: 1px solid #dee2e6; }
.modal-backdrop { position: fixed; top: 0; left: 0; z-index: 1040; width: 100vw; height: 100vh; background-color: #000; opacity: 0.5; }
"""
BS4_MODAL_JS = """
function openModal(el) {
el.classList.add('show');
el.setAttribute('aria-hidden', 'false');
document.body.classList.add('modal-open');
if (!document.querySelector('.modal-backdrop')) {
const bd = document.createElement('div');
bd.className = 'modal-backdrop show';
document.body.appendChild(bd);
}
}
function closeModal(el) {
el.classList.remove('show');
el.setAttribute('aria-hidden', 'true');
document.body.classList.remove('modal-open');
document.querySelectorAll('.modal-backdrop').forEach(b => b.remove());
}
document.querySelectorAll('[data-toggle="modal"]').forEach(btn => {
btn.addEventListener('click', () => {
const m = document.querySelector(btn.getAttribute('data-target'));
if (m) openModal(m);
});
});
document.querySelectorAll('[data-dismiss="modal"]').forEach(btn => {
btn.addEventListener('click', () => {
const m = btn.closest('.modal');
if (m) closeModal(m);
});
});
document.querySelectorAll('.modal').forEach(m => {
m.addEventListener('click', e => { if (e.target === m) closeModal(m); });
});
document.addEventListener('keydown', e => {
if (e.key === 'Escape') {
document.querySelectorAll('.modal.show').forEach(closeModal);
}
});
"""
def launch_browser(p):
try:
return p.chromium.launch(headless=True)
except Exception:
return p.chromium.launch(headless=True, channel="chrome")
def run():
cases = []
with sync_playwright() as p:
browser = launch_browser(p)
page = browser.new_page(viewport={"width": 1200, "height": 800})
page.set_content(f"""<!DOCTYPE html><html><head><style>{BS4_MODAL_CSS}</style></head><body>
<button id="open-btn" type="button" data-toggle="modal" data-target="#myModal">打开模态框</button>
<div class="modal fade" id="myModal" aria-hidden="true">
<div class="modal-dialog" id="dlg-default">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">模态框头部</h4>
<button id="hdr-close" type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">模态框内容..</div>
<div class="modal-footer">
<button id="ftr-close" type="button" data-dismiss="modal">关闭</button>
</div>
</div>
</div>
</div>
<div class="modal show" id="size-probe" style="position:static;display:block;height:auto;">
<div class="modal-dialog modal-sm" id="dlg-sm"><div class="modal-content">SM</div></div>
<div class="modal-dialog" id="dlg-md"><div class="modal-content">MD</div></div>
<div class="modal-dialog modal-lg" id="dlg-lg"><div class="modal-content">LG</div></div>
</div>
<script>{BS4_MODAL_JS}</script></body></html>""")
# Case 1: modal open/close via header close & footer dismiss
def snap():
return page.evaluate("""() => ({
display: getComputedStyle(document.querySelector('#myModal')).display,
zIndex: getComputedStyle(document.querySelector('#myModal')).zIndex,
bodyModalOpen: document.body.classList.contains('modal-open'),
bodyOverflow: getComputedStyle(document.body).overflow,
backdropCount: document.querySelectorAll('.modal-backdrop').length,
})""")
s_init = snap()
page.click("#open-btn")
s_open = snap()
page.click("#hdr-close")
s_after_hdr = snap()
page.click("#open-btn")
page.click("#ftr-close")
s_after_ftr = snap()
actual1 = {
"initial_display": s_init["display"],
"open_display": s_open["display"],
"open_z_index": s_open["zIndex"],
"open_body_overflow": s_open["bodyOverflow"],
"open_backdrop_count": s_open["backdropCount"],
"after_header_close_display": s_after_hdr["display"],
"after_header_close_backdrops": s_after_hdr["backdropCount"],
"after_footer_close_display": s_after_ftr["display"],
"after_footer_close_body_open": s_after_ftr["bodyModalOpen"],
}
expected1 = {
"initial_display": "none",
"open_display": "block",
"open_z_index": "1050",
"open_body_overflow": "hidden",
"open_backdrop_count": 1,
"after_header_close_display": "none",
"after_header_close_backdrops": 0,
"after_footer_close_display": "none",
"after_footer_close_body_open": False,
}
cases.append(dict(
name="modal_open_and_close_lifecycle",
expected=expected1,
actual=actual1,
passed=(actual1 == expected1),
))
# Case 2: modal-sm / default / modal-lg widths at 1200px viewport
actual2 = page.evaluate("""() => ({
sm_width_px: Math.round(document.querySelector('#dlg-sm').getBoundingClientRect().width),
default_width_px: Math.round(document.querySelector('#dlg-md').getBoundingClientRect().width),
lg_width_px: Math.round(document.querySelector('#dlg-lg').getBoundingClientRect().width),
})""")
expected2 = {
"sm_width_px": 300,
"default_width_px": 500,
"lg_width_px": 800,
}
cases.append(dict(
name="modal_dialog_sizes",
expected=expected2,
actual=actual2,
passed=(actual2 == expected2),
))
# Case 3: ESC key and outer overlay click dismiss
page.click("#open-btn")
page.keyboard.press("Escape")
after_esc = snap()["display"]
page.click("#open-btn")
page.mouse.click(10, 10)
after_outside = snap()
actual3 = {
"after_escape_display": after_esc,
"after_outside_click_display": after_outside["display"],
"after_outside_click_backdrops": after_outside["backdropCount"],
}
expected3 = {
"after_escape_display": "none",
"after_outside_click_display": "none",
"after_outside_click_backdrops": 0,
}
cases.append(dict(
name="modal_backdrop_click_and_escape",
expected=expected3,
actual=actual3,
passed=(actual3 == expected3),
))
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
run()
- 核对打开后 display=block、z-index=1050、body overflow=hidden、遮罩数为 1,经头部/底部按钮与 ESC/遮罩外点击均可完全关闭复位,以及 1200px 视口下宽度分别为 300px、500px、800px。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:5d589caecf1f79bf7ce9eac6983df112e2f13a2d9ace91ab50056270332942e0
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:ff6689afcd10fbe0cc080aa1048cf75adcc342e0c1311485cd34c9cf3a6813e2
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
为什么 `.modal-sm` 和 `.modal-lg` 必须写在 `.modal-dialog` 上而不是最外层 `.modal` 上?
展开参考解答
`.modal` 负责全屏固定覆盖视口并接收背景点击事件,真正限制对话框最大宽度与水平居中的容器是内层 `.modal-dialog`,因此尺寸类必须作用于 `.modal-dialog` 才会生效。