"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/bootstrap4-modal-lab/explore-modal.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-modal.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a686.zip
课程关联工程包(登记关联35章) · 含当前章节或实例 · mbskycom202612a664.zip