蓝色天空网mbsky.com · 知识 · 实践 · 创造Bootstrap5 · 本地阅读预览
教程 / 前端开发 / Bootstrap5

Bootstrap5 弹出框

核对 Bootstrap 5 弹出框(Popover)的标题与正文属性、JavaScript 初始化、默认右侧与四方向定位,以及点击/失焦/悬停触发模式。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

创建弹出框与 JavaScript 初始化

弹出框(Popover)类似提示框,但默认通过点击触发,并支持同时展示标题与较长正文。HTML 侧在触发元素添加 `data-bs-toggle="popover"`,用 `title` 指定标题栏、用 `data-bs-content` 提供正文内容,同时须在 JavaScript 中遍历 `[data-bs-toggle="popover"]` 并执行 `new bootstrap.Popover(popoverTriggerEl)` 进行初始化。离线 Chromium 实测初始化 7 个控件后,首次点击默认按钮弹出 `.popover.show`,其中 `.popover-header` 为“弹出框标题”、`.popover-body` 为“弹出框内容”,再次点击同一按钮后弹出框关闭(存活数为 0)。

弹出方向与关闭/悬停触发策略

与提示框默认居上不同,弹出框默认出现在触发元素右侧(实测默认弹出框左边缘位于按钮右边缘之外)。通过 `data-bs-placement` 可改为 `top`、`bottom`、`left` 或 `right`,实测四个方向触发链接的弹出浮层均精确落在对应方位边界外侧。

默认触发方式下需再次点击同一触发器才能关闭弹出框;若希望点击页面外部空白区域即自动关闭,可设置 `data-bs-trigger="focus"`(建议配合可聚焦 `<a>` 或 `tabindex="0"` 保证跨浏览器失焦兼容)。若希望鼠标移入即显示、移出即隐藏,则将属性设为 `data-bs-trigger="hover"`。离线 Chromium 实测验证:`focus` 模式点击外部空白区后弹出框立即销毁(`1 → 0`),`hover` 模式移入显示(`1`)并在移离后销毁(`0`)。

离线 Chromium 核验 Bootstrap 5 弹出框点击切换、四方向定位与 focus/hover 触发

python · 阅读源码
"""Offline Playwright Chromium verification for Bootstrap 5 Popover (Ch 26)."""
import json
from playwright.sync_api import sync_playwright

BS5_POPOVER_CSS = """
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; height: 600px; }
.stage { padding: 140px 260px; display: flex; flex-wrap: wrap; gap: 36px; align-items: center; }
.btn { padding: 8px 16px; background: #0d6efd; color: #fff; border: 0; border-radius: 4px; cursor: pointer; }
.popover { position: fixed; z-index: 1070; max-width: 276px; font-size: 14px; background: #fff; border: 1px solid rgba(0,0,0,.2); border-radius: 6px; box-shadow: 0 4px 12px rgba(0,0,0,.12); }
.popover-header { padding: 8px 16px; margin: 0; font-size: 15px; background: #f0f0f0; border-bottom: 1px solid rgba(0,0,0,.15); border-radius: 5px 5px 0 0; }
.popover-body { padding: 12px 16px; color: #212529; }
"""

BS5_POPOVER_JS = """
window.bootstrap = window.bootstrap || {};
window.bootstrap.Popover = class Popover {
  constructor(el) {
    this.el = el;
    const orig = el.getAttribute('title') || '';
    el.setAttribute('data-bs-original-title', orig);
    el.removeAttribute('title');
    this.placement = el.getAttribute('data-bs-placement') || 'right';
    this.trigger = el.getAttribute('data-bs-trigger') || 'click';
    this.pop = null;
    if (this.trigger === 'click') {
      el.addEventListener('click', e => { e.preventDefault(); this.toggle(); });
    } else if (this.trigger === 'focus') {
      el.addEventListener('click', e => { e.preventDefault(); el.focus(); this.show(); });
      el.addEventListener('blur', () => this.hide());
    } else if (this.trigger === 'hover') {
      el.addEventListener('mouseenter', () => this.show());
      el.addEventListener('mouseleave', () => this.hide());
    }
  }
  toggle() { this.pop ? this.hide() : this.show(); }
  show() {
    if (this.pop) return;
    const pop = document.createElement('div');
    pop.className = 'popover show bs-popover-' + this.placement;
    pop.setAttribute('role', 'tooltip');
    const hdr = document.createElement('h3');
    hdr.className = 'popover-header';
    hdr.textContent = this.el.getAttribute('data-bs-original-title');
    const body = document.createElement('div');
    body.className = 'popover-body';
    body.textContent = this.el.getAttribute('data-bs-content') || '';
    pop.appendChild(hdr);
    pop.appendChild(body);
    document.body.appendChild(pop);
    const tr = this.el.getBoundingClientRect();
    const pr = pop.getBoundingClientRect();
    const gap = 8;
    let top = 0, left = 0;
    if (this.placement === 'top') {
      top = tr.top - pr.height - gap;
      left = tr.left + (tr.width - pr.width) / 2;
    } else if (this.placement === 'bottom') {
      top = tr.bottom + gap;
      left = tr.left + (tr.width - pr.width) / 2;
    } else if (this.placement === 'left') {
      top = tr.top + (tr.height - pr.height) / 2;
      left = tr.left - pr.width - gap;
    } else {
      top = tr.top + (tr.height - pr.height) / 2;
      left = tr.right + gap;
    }
    pop.style.top = top + 'px';
    pop.style.left = left + 'px';
    this.pop = pop;
  }
  hide() {
    if (this.pop) {
      this.pop.remove();
      this.pop = null;
    }
  }
};
const popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
window.__popoverList = popoverTriggerList.map(el => new bootstrap.Popover(el));
"""

HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{BS5_POPOVER_CSS}</style></head>
<body>
<div id="outside" style="padding:12px;">外部空白区域</div>
<div class="stage">
  <button id="pop-default" type="button" class="btn" data-bs-toggle="popover" title="弹出框标题" data-bs-content="弹出框内容">多次点我</button>
  <a id="pop-top" href="#" data-bs-toggle="popover" data-bs-placement="top" title="标题" data-bs-content="上方内容">Top</a>
  <a id="pop-bottom" href="#" data-bs-toggle="popover" data-bs-placement="bottom" title="标题" data-bs-content="下方内容">Bottom</a>
  <a id="pop-left" href="#" data-bs-toggle="popover" data-bs-placement="left" title="标题" data-bs-content="左侧内容">Left</a>
  <a id="pop-right" href="#" data-bs-toggle="popover" data-bs-placement="right" title="标题" data-bs-content="右侧内容">Right</a>
  <a id="pop-focus" href="#" tabindex="0" data-bs-toggle="popover" data-bs-trigger="focus" title="取消弹出框" data-bs-content="点击外部关闭">Focus</a>
  <a id="pop-hover" href="#" data-bs-toggle="popover" data-bs-trigger="hover" title="悬停标题" data-bs-content="悬停内容">Hover</a>
</div>
<script>{BS5_POPOVER_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": 1000, "height": 600})
        page.set_content(HTML_DOC)

        # Case 1: click toggle and title/content rendering
        init_count = page.evaluate("() => window.__popoverList.length")
        page.click("#pop-default")
        first_click = page.evaluate("""() => {
            const pop = document.querySelector('.popover.show');
            const tr = document.querySelector('#pop-default').getBoundingClientRect();
            const pr = pop.getBoundingClientRect();
            return {
                header: pop.querySelector('.popover-header').textContent,
                body: pop.querySelector('.popover-body').textContent,
                default_on_right: pr.left > tr.right,
            };
        }""")
        page.click("#pop-default")
        second_click_count = page.eval_on_selector_all(".popover.show", "els => els.length")
        c1_actual = {"init_count": init_count, "first_click": first_click, "after_second_click": second_click_count}
        c1_expected = {
            "init_count": 7,
            "first_click": {"header": "弹出框标题", "body": "弹出框内容", "default_on_right": True},
            "after_second_click": 0,
        }
        cases.append({
            "name": "popover_init_and_click_toggle",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        })

        # Case 2: four placements geometry
        pos_ok = {}
        for pos, sel in [("top", "#pop-top"), ("bottom", "#pop-bottom"), ("left", "#pop-left"), ("right", "#pop-right")]:
            page.click(sel)
            ok = page.evaluate("""([sel, pos]) => {
                const tr = document.querySelector(sel).getBoundingClientRect();
                const pr = document.querySelector('.popover.show').getBoundingClientRect();
                if (pos === 'top') return pr.bottom < tr.top;
                if (pos === 'bottom') return pr.top > tr.bottom;
                if (pos === 'left') return pr.right < tr.left;
                if (pos === 'right') return pr.left > tr.right;
                return false;
            }""", [sel, pos])
            pos_ok[pos] = ok
            page.click(sel)
        c2_expected = {"top": True, "bottom": True, "left": True, "right": True}
        cases.append({
            "name": "popover_four_placements_and_default_right",
            "expected": c2_expected,
            "actual": pos_ok,
            "passed": pos_ok == c2_expected,
        })

        # Case 3: focus dismiss on outside click & hover trigger
        page.click("#pop-focus")
        focus_open = page.eval_on_selector_all(".popover.show", "els => els.length")
        page.click("#outside")
        focus_closed = page.eval_on_selector_all(".popover.show", "els => els.length")
        page.hover("#pop-hover")
        hover_open = page.eval_on_selector_all(".popover.show", "els => els.length")
        page.mouse.move(10, 10)
        hover_closed = page.eval_on_selector_all(".popover.show", "els => els.length")
        c3_actual = {
            "focus_open": focus_open,
            "focus_after_outside_click": focus_closed,
            "hover_open": hover_open,
            "hover_after_leave": hover_closed,
        }
        c3_expected = {
            "focus_open": 1,
            "focus_after_outside_click": 0,
            "hover_open": 1,
            "hover_after_leave": 0,
        }
        cases.append({
            "name": "popover_trigger_focus_and_hover",
            "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()
预期结果 · 待实际运行核验
  • 核对 new bootstrap.Popover 初始化、首次/二次点击显隐与标题正文、默认右侧与 top/bottom/left/right 方位,以及 focus 失焦关闭和 hover 移入移出。
离线 Chromium 核验 Bootstrap 5 弹出框点击切换、四方向定位与 focus/hover 触发

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:5bf7abfe75b66fc857792801520f995d86b2a4e705ca574febf2707d91fe1325

下载本站示例源码

本地运行

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

下载Bootstrap5 弹出框实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:854d22dc6fed3909b0dadad8ae3b9491ce202ef753867c45e017ba84d46018de

常见错误与边界

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

练习与解答

在 Bootstrap 5 中,Tooltip 与 Popover 在默认展示位置、触发方式和内容属性上有哪些主要区别?

展开参考解答

Tooltip 默认在元素上方且以悬停/聚焦触发,仅用 `title` 显示单段简短文本;Popover 默认在元素右侧且以点击触发,除 `title` 标题外还通过 `data-bs-content` 承载正文,并可用 `data-bs-trigger="focus"` 或 `"hover"` 调整交互。

规范与官方依据