Bootstrap5 消息弹窗
核对 Bootstrap 5 消息弹窗(Toasts)的默认隐藏与关闭按钮、JavaScript 批量触发、角落固定定位及多条堆叠容器用法。
学完这一章,你能够
- 核对 Bootstrap 5 消息弹窗(Toasts)的默认隐藏与关闭按钮、JavaScript 批量触发、角落固定定位及多条堆叠容器用法。
消息弹窗基础结构与默认状态
消息弹窗(Toast)是面向短期反馈(成功、错误、警告或系统提醒)的轻量级非阻塞通知组件,可灵活布局在视口四角或底部中央。其结构以外层 `.toast` 包裹 `.toast-header`(标题与关闭按钮)和 `.toast-body`(通知正文)。默认状态下 `.toast` 保持隐藏,需叠加 `.show` 或通过脚本显示;关闭按钮在 `<button class="btn-close">` 上声明 `data-bs-dismiss="toast"`。离线 Chromium 实测未加 `.show` 的 `.toast` 为 `display: none`,含 `.show` 者为 `display: block`,点击关闭按钮后恢复 `display: none`。
脚本触发显示、固定角落与多弹窗堆叠
由业务按钮按需弹出消息时,在按钮点击事件中选取目标 `.toast` 元素,使用 Bootstrap 5 的 `new bootstrap.Toast(toastEl)` 实例化并调用 `.show()` 即可(注意无需旧版 jQuery `.toast()` 写法)。实测点击 `#toastbtn` 后,页面内 2 个初始隐藏的消息弹窗同步添加 `.show` 并转为 `display: block`。
将弹窗固定在页面右下角时,外层使用 `.position-fixed.bottom-0.end-0.p-3` 包裹带 `role="alert"`、`aria-live="assertive"` 与 `aria-atomic="true"` 的 `.toast`,实测在 `800×600` 视口中弹窗右边与底边稳定落于 `(784, 584)`(内缩 `16px` 边距)。同时展示多条消息时,应使用 `.toast-container`(可组合 `top-0 end-0 p-3`)统一承载并自动维持垂直间距,实测两条堆叠弹窗间隔 `12px`,关闭第一条后仅第一条隐藏、第二条继续保持可见。
离线 Chromium 核验 Bootstrap 5 消息弹窗显隐、脚本批量展示与多条堆叠定位
"""Offline Playwright Chromium verification for Bootstrap 5 Toasts (Ch 27)."""
import json
from playwright.sync_api import sync_playwright
BS5_TOAST_CSS = """
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; height: 600px; }
.toast { width: 350px; max-width: 100%; font-size: 14px; background: rgba(255,255,255,.95); border: 1px solid rgba(0,0,0,.1); box-shadow: 0 8px 16px rgba(0,0,0,.15); border-radius: 4px; display: none; }
.toast.show { display: block; }
.toast-header { display: flex; align-items: center; padding: 8px 12px; color: #6c757d; background: rgba(255,255,255,.85); border-bottom: 1px solid rgba(0,0,0,.05); }
.toast-body { padding: 12px; }
.me-auto { margin-right: auto !important; }
.btn-close { border: 0; background: transparent; cursor: pointer; font-weight: bold; }
.position-fixed { position: fixed !important; }
.position-relative { position: relative !important; }
.top-0 { top: 0 !important; }
.bottom-0 { bottom: 0 !important; }
.end-0 { right: 0 !important; }
.p-3 { padding: 16px !important; }
.toast-container { width: max-content; max-width: 100%; }
.toast-container > :not(:last-child) { margin-bottom: 12px; }
"""
BS5_TOAST_JS = """
window.bootstrap = window.bootstrap || {};
window.bootstrap.Toast = class Toast {
constructor(el) { this.el = el; }
show() { this.el.classList.add('show'); }
hide() { this.el.classList.remove('show'); }
};
document.querySelectorAll('[data-bs-dismiss="toast"]').forEach(btn => {
btn.addEventListener('click', () => {
const t = btn.closest('.toast');
if (t) t.classList.remove('show');
});
});
document.getElementById('toastbtn').onclick = function() {
const toastElList = [].slice.call(document.querySelectorAll('#batch-zone .toast'));
const toastList = toastElList.map(el => new bootstrap.Toast(el));
toastList.forEach(t => t.show());
};
"""
HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{BS5_TOAST_CSS}</style></head>
<body>
<div id="basic-hidden" class="toast">
<div class="toast-header"><strong class="me-auto">默认隐藏</strong></div>
<div class="toast-body">未添加 .show 时隐藏</div>
</div>
<div id="basic-shown" class="toast show">
<div class="toast-header">
<strong class="me-auto">弹窗标题</strong>
<button id="dismiss-basic" type="button" class="btn-close" data-bs-dismiss="toast">x</button>
</div>
<div class="toast-body">这是一个 Bootstrap 5 弹窗示例。</div>
</div>
<div id="batch-zone">
<button id="toastbtn" type="button">显示全部 Toast</button>
<div id="batch-t1" class="toast"><div class="toast-body">消息 A</div></div>
<div id="batch-t2" class="toast"><div class="toast-body">消息 B</div></div>
</div>
<div id="br-wrap" class="position-fixed bottom-0 end-0 p-3">
<div id="br-toast" class="toast show" role="alert" aria-live="assertive" aria-atomic="true">
<div class="toast-header">
<strong class="me-auto">Bootstrap Toast</strong>
<button type="button" class="btn-close" data-bs-dismiss="toast">x</button>
</div>
<div class="toast-body">右下角固定消息</div>
</div>
</div>
<div aria-live="polite" aria-atomic="true" class="position-relative">
<div id="stack-box" class="toast-container top-0 end-0 p-3">
<div id="stack-t1" class="toast fade show" role="alert">
<div class="toast-header">
<strong class="me-auto">弹窗实例</strong>
<small>刚刚</small>
<button id="close-stack-1" type="button" class="btn-close" data-bs-dismiss="toast">x</button>
</div>
<div class="toast-body">这是第二个消息</div>
</div>
<div id="stack-t2" class="toast fade show" role="alert">
<div class="toast-header">
<strong class="me-auto">弹窗实例</strong>
<small>2 秒前</small>
<button type="button" class="btn-close" data-bs-dismiss="toast">x</button>
</div>
<div class="toast-body">这是第一个消息</div>
</div>
</div>
</div>
<script>{BS5_TOAST_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": 800, "height": 600})
page.set_content(HTML_DOC)
# Case 1: default hidden, .show visible, data-bs-dismiss closes
before = page.evaluate("""() => ({
hidden_default: getComputedStyle(document.querySelector('#basic-hidden')).display,
shown_default: getComputedStyle(document.querySelector('#basic-shown')).display,
})""")
page.click("#dismiss-basic")
after_dismiss = page.eval_on_selector("#basic-shown", "el => getComputedStyle(el).display")
c1_actual = {**before, "after_dismiss": after_dismiss}
c1_expected = {"hidden_default": "none", "shown_default": "block", "after_dismiss": "none"}
cases.append({
"name": "toast_default_hidden_show_and_dismiss",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
})
# Case 2: JS batch show on button click
before_batch = page.eval_on_selector_all("#batch-zone .toast.show", "els => els.length")
page.click("#toastbtn")
after_batch = page.evaluate("""() => ({
shown_count: document.querySelectorAll('#batch-zone .toast.show').length,
displays: ['#batch-t1', '#batch-t2'].map(s => getComputedStyle(document.querySelector(s)).display),
})""")
c2_actual = {"before_click_shown": before_batch, **after_batch}
c2_expected = {"before_click_shown": 0, "shown_count": 2, "displays": ["block", "block"]}
cases.append({
"name": "toast_js_batch_trigger_show",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
})
# Case 3: bottom-right fixed corner & toast-container multi-toast stacking
layout = page.evaluate("""() => {
const wrap = document.querySelector('#br-wrap');
const wcs = getComputedStyle(wrap);
const brRect = document.querySelector('#br-toast').getBoundingClientRect();
const r1 = document.querySelector('#stack-t1').getBoundingClientRect();
const r2 = document.querySelector('#stack-t2').getBoundingClientRect();
return {
wrap_position: wcs.position,
wrap_bottom: wcs.bottom,
wrap_right: wcs.right,
br_toast_right_edge: Math.round(brRect.right),
br_toast_bottom_edge: Math.round(brRect.bottom),
stack_gap_px: Math.round(r2.top - r1.bottom),
};
}""")
page.click("#close-stack-1")
after_stack_close = page.evaluate("""() => ({
t1_display: getComputedStyle(document.querySelector('#stack-t1')).display,
t2_display: getComputedStyle(document.querySelector('#stack-t2')).display,
})""")
c3_actual = {**layout, **after_stack_close}
c3_expected = {
"wrap_position": "fixed",
"wrap_bottom": "0px",
"wrap_right": "0px",
"br_toast_right_edge": 784,
"br_toast_bottom_edge": 584,
"stack_gap_px": 12,
"t1_display": "none",
"t2_display": "block",
}
cases.append({
"name": "toast_bottom_end_fixed_and_container_stacking",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
})
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 核对 .toast 默认隐藏与 data-bs-dismiss 关闭、按钮触发批量 new bootstrap.Toast().show()、.position-fixed.bottom-0.end-0.p-3 右下定位及 .toast-container 12px 垂直间距与独立关闭。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
当前源码 SHA256:9af2dd72b71e0d8a542e0ad8e1df5d938a0bc83dfd99c9287499e7b1a2ae0b7b
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
ZIP SHA256:ee74aade2fbca404ab042f96ce32f6a02c077bc1705352c431708a625c83c05c
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
多条 Toast 消息同时出现时,为什么要把它们放进 `.toast-container` 容器而不是直接叠加多个 `.position-fixed` 元素?
展开参考解答
直接叠加多个 `.position-fixed` 弹窗会导致它们在同一坐标相互遮挡;放入 `.toast-container` 后,容器自动按垂直流排布多条通知并提供统一间距,且每条通知可独立关闭互不干扰。