蓝色天空.知识 · 实践 · 创造
我的收藏
Bootstrap5 教程目录 38章
Bootstrap5 / LEARN BY DOING

Bootstrap5 模态框

核对 Bootstrap 5 模态框层级结构、淡入动画、尺寸变体、全屏与响应式全屏断点、垂直居中及内部滚动条机制。

学完这一章,你能够

  • 核对 Bootstrap 5 模态框层级结构、淡入动画、尺寸变体、全屏与响应式全屏断点、垂直居中及内部滚动条机制。

模态框基础结构与开关动画

模态框(Modal)是覆盖在主页面之上的交互对话框,用于在当前视图中承载表单、确认提示或详情内容。标准结构由触发按钮(`data-bs-toggle="modal"`、`data-bs-target="#myModal"`)与嵌套层级 `.modal > .modal-dialog > .modal-content` 组成,内容区按 `.modal-header`(含 `.modal-title` 与带 `data-bs-dismiss="modal"` 的 `.btn-close`)、`.modal-body` 和 `.modal-footer` 分块。在 `.modal` 上叠加 `.fade` 可启用透明度过渡(实测 `transition-property: opacity`),省略 `.fade` 则即时显隐;实测点击打开按钮后模态框由 `display: none` 变为 `display: block` 且 `aria-hidden="false"`,点击右上角关闭按钮或底部关闭按钮均可恢复隐藏。

尺寸变体与响应式全屏断点

通过在 `.modal-dialog` 上追加尺寸修饰类可调整弹窗最大宽度:离线 Chromium 在 `1280px` 视口实测默认对话框为 `500px`,`.modal-sm` 为 `300px`,`.modal-lg` 为 `800px`,`.modal-xl` 为 `1140px`。需要铺满整个视口时使用 `.modal-fullscreen`(实测 `max-width: none`、`100vw` 铺满),若希望仅在特定断点以下全屏显示、超过断点后恢复 `500px` 弹窗宽度,则使用下表 5 个响应式全屏类。

垂直居中与内容区独立滚动

在 `.modal-dialog` 上添加 `.modal-dialog-centered` 可借助 Flex 纵轴对齐使模态框在视口水平与垂直方向均居中(实测 `600px` 高视口内内容框垂直中点精确落于 `300px`)。当正文较长时,默认 `.modal-dialog` 由外层 `.modal` 随页面高度整体滚动;若希望固定头尾而仅让 `.modal-body` 内部出现滚动条,应改用 `.modal-dialog-scrollable`。实测 `.modal-dialog-scrollable` 的 `.modal-body` 具备 `overflow-y: auto` 且 `scrollHeight > clientHeight`,将其内部 `scrollTop` 滚至 `120px` 时外层 `.modal` 保持 `scrollTop = 0`。

Bootstrap 5 响应式全屏模态框断点对照

类名全屏生效条件与实测结果
.modal-fullscreen-sm-down视口宽度低于 `576px` 时全屏(实测 `500px` 为 `none`,`600px` 恢复 `500px`)
.modal-fullscreen-md-down视口宽度低于 `768px` 时全屏(实测 `700px` 为 `none`,`800px` 恢复 `500px`)
.modal-fullscreen-lg-down视口宽度低于 `992px` 时全屏(实测 `900px` 为 `none`,`1024px` 恢复 `500px`)
.modal-fullscreen-xl-down视口宽度低于 `1200px` 时全屏(实测 `1100px` 为 `none`,`1240px` 恢复 `500px`)
.modal-fullscreen-xxl-down视口宽度低于 `1400px` 时全屏(实测 `1300px` 为 `none`,`1440px` 恢复 `500px`)

离线 Chromium 核验 Bootstrap 5 模态框开关、四档尺寸、五级全屏断点与内滚

含完整源码 · 259 行
展开查看收起
python
"""Offline Playwright Chromium verification for Bootstrap 5 Modal (Ch 24)."""
import json
from playwright.sync_api import sync_playwright

BS5_MODAL_CSS = """
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; }
.modal { position: fixed; top: 0; left: 0; z-index: 1055; display: none; width: 100%; height: 100%; overflow-x: hidden; overflow-y: auto; outline: 0; background: rgba(0,0,0,0.45); }
.modal.show { display: block; }
.modal.fade { transition: opacity 0.15s linear; opacity: 0; }
.modal.fade.show { opacity: 1; }
.modal-dialog { position: relative; width: auto; max-width: 500px; margin: 28px auto; pointer-events: none; }
.modal-content { position: relative; display: flex; flex-direction: column; width: 100%; pointer-events: auto; background: #fff; border: 1px solid rgba(0,0,0,.2); border-radius: 6px; }
.modal-header { display: flex; align-items: center; justify-content: space-between; padding: 16px; border-bottom: 1px solid #dee2e6; }
.modal-body { position: relative; flex: 1 1 auto; padding: 16px; }
.modal-footer { display: flex; justify-content: flex-end; padding: 12px; border-top: 1px solid #dee2e6; }
.modal-sm { max-width: 300px; }
.modal-lg { max-width: 800px; }
.modal-xl { max-width: 1140px; }
.modal-dialog-centered { display: flex; align-items: center; min-height: calc(100% - 56px); }
.modal-dialog-scrollable { height: calc(100% - 56px); }
.modal-dialog-scrollable .modal-content { max-height: 100%; overflow: hidden; }
.modal-dialog-scrollable .modal-body { overflow-y: auto; }
.modal-fullscreen { width: 100vw; max-width: none; height: 100%; margin: 0; }
.modal-fullscreen .modal-content { height: 100%; border: 0; border-radius: 0; }
@media (max-width: 575.98px) { .modal-fullscreen-sm-down { width: 100vw; max-width: none; height: 100%; margin: 0; } }
@media (max-width: 767.98px) { .modal-fullscreen-md-down { width: 100vw; max-width: none; height: 100%; margin: 0; } }
@media (max-width: 991.98px) { .modal-fullscreen-lg-down { width: 100vw; max-width: none; height: 100%; margin: 0; } }
@media (max-width: 1199.98px) { .modal-fullscreen-xl-down { width: 100vw; max-width: none; height: 100%; margin: 0; } }
@media (max-width: 1399.98px) { .modal-fullscreen-xxl-down { width: 100vw; max-width: none; height: 100%; margin: 0; } }
"""

BS5_MODAL_JS = """
document.querySelectorAll('[data-bs-toggle="modal"]').forEach(btn => {
  btn.addEventListener('click', () => {
    const m = document.querySelector(btn.getAttribute('data-bs-target'));
    m.classList.add('show');
    m.setAttribute('aria-hidden', 'false');
  });
});
document.querySelectorAll('[data-bs-dismiss="modal"]').forEach(btn => {
  btn.addEventListener('click', () => {
    const m = btn.closest('.modal');
    m.classList.remove('show');
    m.setAttribute('aria-hidden', 'true');
  });
});
"""

LONG_TEXT = "".join(f"<p>长文本段落 {i}</p>" for i in range(1, 35))

HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{BS5_MODAL_CSS}</style></head>
<body>
  <button id="open-fade" type="button" data-bs-toggle="modal" data-bs-target="#myModal">打开模态框</button>
  <div class="modal fade" id="myModal" role="dialog" aria-hidden="true">
    <div id="dlg-default" class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h4 class="modal-title">模态框标题</h4>
          <button id="close-x" type="button" class="btn-close" data-bs-dismiss="modal">x</button>
        </div>
        <div class="modal-body">模态框内容</div>
        <div class="modal-footer">
          <button id="close-btn" type="button" data-bs-dismiss="modal">关闭</button>
        </div>
      </div>
    </div>
  </div>

  <div class="modal" id="plainModal"><div class="modal-dialog"><div class="modal-content"></div></div></div>

  <div class="modal show" id="sizeStage" style="position:static;height:auto;background:transparent;">
    <div id="dlg-sm" class="modal-dialog modal-sm"><div class="modal-content"><div class="modal-body">SM</div></div></div>
    <div id="dlg-base" class="modal-dialog"><div class="modal-content"><div class="modal-body">Base</div></div></div>
    <div id="dlg-lg" class="modal-dialog modal-lg"><div class="modal-content"><div class="modal-body">LG</div></div></div>
    <div id="dlg-xl" class="modal-dialog modal-xl"><div class="modal-content"><div class="modal-body">XL</div></div></div>
    <div id="dlg-fs" class="modal-dialog modal-fullscreen"><div class="modal-content"><div class="modal-body">FS</div></div></div>
    <div id="dlg-fs-sm" class="modal-dialog modal-fullscreen-sm-down"><div class="modal-content"><div class="modal-body">FS-SM</div></div></div>
    <div id="dlg-fs-md" class="modal-dialog modal-fullscreen-md-down"><div class="modal-content"><div class="modal-body">FS-MD</div></div></div>
    <div id="dlg-fs-lg" class="modal-dialog modal-fullscreen-lg-down"><div class="modal-content"><div class="modal-body">FS-LG</div></div></div>
    <div id="dlg-fs-xl" class="modal-dialog modal-fullscreen-xl-down"><div class="modal-content"><div class="modal-body">FS-XL</div></div></div>
    <div id="dlg-fs-xxl" class="modal-dialog modal-fullscreen-xxl-down"><div class="modal-content"><div class="modal-body">FS-XXL</div></div></div>
  </div>

  <div class="modal" id="centeredModal">
    <div id="dlg-centered" class="modal-dialog modal-dialog-centered">
      <div class="modal-content" style="height:120px;"><div class="modal-body">Centered</div></div>
    </div>
  </div>

  <div class="modal" id="scrollModal">
    <div id="dlg-scroll" class="modal-dialog modal-dialog-scrollable">
      <div class="modal-content">
        <div class="modal-header"><h4>Scrollable</h4></div>
        <div id="scroll-body" class="modal-body">{LONG_TEXT}</div>
        <div class="modal-footer"><span>Footer</span></div>
      </div>
    </div>
  </div>
<script>{BS5_MODAL_JS}</script>
</body>
</html>
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 1280, "height": 600})
        page.set_content(HTML_DOC)

        # Case 1: toggle, dismiss, fade vs plain
        before_disp = page.eval_on_selector("#myModal", "el => getComputedStyle(el).display")
        page.click("#open-fade")
        opened = page.evaluate("""() => ({
            display: getComputedStyle(document.querySelector('#myModal')).display,
            aria_hidden: document.querySelector('#myModal').getAttribute('aria-hidden'),
            fade_prop: getComputedStyle(document.querySelector('#myModal')).transitionProperty,
            plain_prop: getComputedStyle(document.querySelector('#plainModal')).transitionProperty,
        })""")
        page.click("#close-x")
        closed_x = page.eval_on_selector("#myModal", "el => getComputedStyle(el).display")
        page.click("#open-fade")
        page.click("#close-btn")
        closed_btn = page.eval_on_selector("#myModal", "el => getComputedStyle(el).display")
        c1_actual = {
            "before_display": before_disp,
            "opened": opened,
            "after_close_x": closed_x,
            "after_close_btn": closed_btn,
        }
        c1_expected = {
            "before_display": "none",
            "opened": {
                "display": "block",
                "aria_hidden": "false",
                "fade_prop": "opacity",
                "plain_prop": "all",
            },
            "after_close_x": "none",
            "after_close_btn": "none",
        }
        cases.append({
            "name": "modal_toggle_dismiss_and_fade",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        })

        # Case 2: modal dialog sizes at 1280px
        c2_actual = page.evaluate("""() => ({
            sm: getComputedStyle(document.querySelector('#dlg-sm')).maxWidth,
            default: getComputedStyle(document.querySelector('#dlg-base')).maxWidth,
            lg: getComputedStyle(document.querySelector('#dlg-lg')).maxWidth,
            xl: getComputedStyle(document.querySelector('#dlg-xl')).maxWidth,
        })""")
        c2_expected = {"sm": "300px", "default": "500px", "lg": "800px", "xl": "1140px"}
        cases.append({
            "name": "modal_dialog_sizes",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        })

        # Case 3: fullscreen & all 5 responsive *-down breakpoints
        fs_matrix = {}
        for vw, sel, label in [
            (1280, "#dlg-fs", "fullscreen_1280"),
            (500, "#dlg-fs-sm", "sm_down_at_500"),
            (600, "#dlg-fs-sm", "sm_down_at_600"),
            (700, "#dlg-fs-md", "md_down_at_700"),
            (800, "#dlg-fs-md", "md_down_at_800"),
            (900, "#dlg-fs-lg", "lg_down_at_900"),
            (1024, "#dlg-fs-lg", "lg_down_at_1024"),
            (1100, "#dlg-fs-xl", "xl_down_at_1100"),
            (1240, "#dlg-fs-xl", "xl_down_at_1240"),
            (1300, "#dlg-fs-xxl", "xxl_down_at_1300"),
            (1440, "#dlg-fs-xxl", "xxl_down_at_1440"),
        ]:
            page.set_viewport_size({"width": vw, "height": 600})
            fs_matrix[label] = page.eval_on_selector(sel, "el => getComputedStyle(el).maxWidth")
        c3_expected = {
            "fullscreen_1280": "none",
            "sm_down_at_500": "none",
            "sm_down_at_600": "500px",
            "md_down_at_700": "none",
            "md_down_at_800": "500px",
            "lg_down_at_900": "none",
            "lg_down_at_1024": "500px",
            "xl_down_at_1100": "none",
            "xl_down_at_1240": "500px",
            "xxl_down_at_1300": "none",
            "xxl_down_at_1440": "500px",
        }
        cases.append({
            "name": "modal_fullscreen_and_responsive_breakpoints",
            "expected": c3_expected,
            "actual": fs_matrix,
            "passed": fs_matrix == c3_expected,
        })

        # Case 4: centered and scrollable dialog
        page.set_viewport_size({"width": 800, "height": 600})
        c4_actual = page.evaluate("""() => {
            const cm = document.querySelector('#centeredModal');
            cm.classList.add('show');
            const cRect = document.querySelector('#centeredModal .modal-content').getBoundingClientRect();
            const centeredMid = Math.round((cRect.top + cRect.bottom) / 2);
            cm.classList.remove('show');

            const sm = document.querySelector('#scrollModal');
            sm.classList.add('show');
            const body = document.querySelector('#scroll-body');
            const bodyOverflow = getComputedStyle(body).overflowY;
            const bodyScrollable = body.scrollHeight > body.clientHeight;
            body.scrollTop = 120;
            const actualScrollTop = Math.round(body.scrollTop);
            const outerScrollTop = Math.round(sm.scrollTop);
            sm.classList.remove('show');
            return {
                centered_mid_y: centeredMid,
                scroll_body_overflow_y: bodyOverflow,
                scroll_body_overflows: bodyScrollable,
                inner_scroll_top: actualScrollTop,
                outer_modal_scroll_top: outerScrollTop,
            };
        }""")
        c4_expected = {
            "centered_mid_y": 300,
            "scroll_body_overflow_y": "auto",
            "scroll_body_overflows": True,
            "inner_scroll_top": 120,
            "outer_modal_scroll_top": 0,
        }
        cases.append({
            "name": "modal_centered_and_scrollable",
            "expected": c4_expected,
            "actual": c4_actual,
            "passed": c4_actual == c4_expected,
        })

        browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
核对模态框打开/关闭与 fade 透明度过渡、sm(300px)/默认(500px)/lg(800px)/xl(1140px) 宽度、5 个 *-down 视口临界切换、垂直居中 300px 及 scrollable 内滚不带动外层。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a700.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Bootstrap5

课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a700.zip

下载课程关联工程包:Bootstrap5

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a723.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

默认模式下整个弹窗随外层 `.modal` 容器滚动,标题栏与底部按钮会滚出视野;添加 `.modal-dialog-scrollable` 后弹窗高度被约束在视口内,仅 `.modal-body` 开启 `overflow-y: auto` 独立滚动,头尾区域始终固定可见。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习