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

Bootstrap5 提示框

核对 Bootstrap 5 提示框(Tooltip)的属性声明、显式 JavaScript 初始化要求、悬停显隐周期与四方向定位。

学完这一章,你能够

  • 核对 Bootstrap 5 提示框(Tooltip)的属性声明、显式 JavaScript 初始化要求、悬停显隐周期与四方向定位。

创建提示框与显式 JavaScript 初始化

提示框(Tooltip)是一种轻量悬停浮层,当鼠标移入目标元素时展示简短说明,移出后自动隐藏。HTML 侧需在目标元素声明 `data-bs-toggle="tooltip"`,并通过 `title` 属性提供提示文案。出于性能考量,Bootstrap 5 不会自动启用页面中的所有提示框,必须在脚本中遍历 `[data-bs-toggle="tooltip"]` 并调用 `new bootstrap.Tooltip(tooltipTriggerEl)` 完成初始化(不再使用旧版 jQuery `.tooltip()` 方法)。离线 Chromium 实测初始化 5 个触发器时,组件会将 `title` 迁移至 `data-bs-original-title` 以避免浏览器原生悬浮气泡重影;悬停默认按钮弹出内容为“我是提示内容!”的 `.tooltip.show`,移开鼠标后浮层计数归零,而未初始化的同类按钮悬停时保持 0 个浮层且保留原生 `title`。

四个方向的定位控制

未指定方向时,提示框默认显示在元素正上方(实测默认提示框底边位于触发按钮顶边之上)。通过设置 `data-bs-placement` 为 `top`、`bottom`、`left` 或 `right`,可明确控制提示框相对触发元素的方位;实测 4 个方位链接在悬停时分别精确渲染于触发器上方、下方、左侧与右侧。

离线 Chromium 核验 Bootstrap 5 提示框初始化、悬停显隐与四方向定位

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

BS5_TOOLTIP_CSS = """
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; height: 600px; }
.stage { padding: 140px 260px; display: flex; flex-direction: column; gap: 36px; align-items: center; }
.btn { padding: 8px 16px; background: #0d6efd; color: #fff; border: 0; border-radius: 4px; cursor: pointer; }
.tooltip { position: fixed; z-index: 1080; display: block; font-size: 14px; opacity: 0; pointer-events: none; }
.tooltip.show { opacity: 0.9; }
.tooltip-inner { max-width: 200px; padding: 4px 8px; color: #fff; text-align: center; background-color: #000; border-radius: 4px; white-space: nowrap; }
"""

BS5_TOOLTIP_JS = """
window.bootstrap = window.bootstrap || {};
window.bootstrap.Tooltip = class Tooltip {
  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') || 'top';
    this.tip = null;
    el.addEventListener('mouseenter', () => this.show());
    el.addEventListener('mouseleave', () => this.hide());
  }
  show() {
    if (this.tip) return;
    const tip = document.createElement('div');
    tip.className = 'tooltip show bs-tooltip-' + this.placement;
    tip.setAttribute('role', 'tooltip');
    const inner = document.createElement('div');
    inner.className = 'tooltip-inner';
    inner.textContent = this.el.getAttribute('data-bs-original-title');
    tip.appendChild(inner);
    document.body.appendChild(tip);
    const tr = this.el.getBoundingClientRect();
    const pr = tip.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 if (this.placement === 'right') {
      top = tr.top + (tr.height - pr.height) / 2;
      left = tr.right + gap;
    }
    tip.style.top = top + 'px';
    tip.style.left = left + 'px';
    this.tip = tip;
  }
  hide() {
    if (this.tip) {
      this.tip.remove();
      this.tip = null;
    }
  }
};
// Initialize all elements inside #init-scope (mimics BS5 opt-in initialization)
const tooltipTriggerList = [].slice.call(document.querySelectorAll('#init-scope [data-bs-toggle="tooltip"]'));
window.__tooltipList = tooltipTriggerList.map(el => new bootstrap.Tooltip(el));
"""

HTML_DOC = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{BS5_TOOLTIP_CSS}</style></head>
<body>
<div class="stage">
  <div id="init-scope" style="display:flex;gap:32px;align-items:center;">
    <button id="tip-default" type="button" class="btn" data-bs-toggle="tooltip" title="我是提示内容!">默认提示</button>
    <a id="tip-top" href="#" data-bs-toggle="tooltip" data-bs-placement="top" title="顶部提示">Top</a>
    <a id="tip-bottom" href="#" data-bs-toggle="tooltip" data-bs-placement="bottom" title="底部提示">Bottom</a>
    <a id="tip-left" href="#" data-bs-toggle="tooltip" data-bs-placement="left" title="左侧提示">Left</a>
    <a id="tip-right" href="#" data-bs-toggle="tooltip" data-bs-placement="right" title="右侧提示">Right</a>
  </div>
  <button id="tip-uninit" type="button" class="btn" data-bs-toggle="tooltip" title="未初始化按钮">未初始化</button>
</div>
<script>{BS5_TOOLTIP_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": 900, "height": 600})
        page.set_content(HTML_DOC)

        # Case 1: initialization & hover lifecycle
        init_meta = page.evaluate("""() => ({
            count: window.__tooltipList.length,
            title_removed: document.querySelector('#tip-default').getAttribute('title') === null,
            original_title: document.querySelector('#tip-default').getAttribute('data-bs-original-title'),
        })""")
        page.hover("#tip-default")
        hover_on = page.evaluate("""() => {
            const tip = document.querySelector('.tooltip.show');
            const tr = document.querySelector('#tip-default').getBoundingClientRect();
            const pr = tip.getBoundingClientRect();
            return {
                visible: Boolean(tip),
                text: tip.querySelector('.tooltip-inner').textContent,
                default_above_trigger: pr.bottom < tr.top,
            };
        }""")
        page.mouse.move(10, 10)
        hover_off = page.eval_on_selector_all(".tooltip.show", "els => els.length")
        c1_actual = {"init": init_meta, "hover_on": hover_on, "hover_off_count": hover_off}
        c1_expected = {
            "init": {"count": 5, "title_removed": True, "original_title": "我是提示内容!"},
            "hover_on": {"visible": True, "text": "我是提示内容!", "default_above_trigger": True},
            "hover_off_count": 0,
        }
        cases.append({
            "name": "tooltip_init_and_hover_lifecycle",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        })

        # Case 2: four placements geometry
        placements = {}
        for pos, sel in [("top", "#tip-top"), ("bottom", "#tip-bottom"), ("left", "#tip-left"), ("right", "#tip-right")]:
            page.hover(sel)
            ok = page.evaluate("""([sel, pos]) => {
                const tr = document.querySelector(sel).getBoundingClientRect();
                const pr = document.querySelector('.tooltip.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])
            placements[pos] = ok
            page.mouse.move(10, 10)
        c2_expected = {"top": True, "bottom": True, "left": True, "right": True}
        cases.append({
            "name": "tooltip_four_placements",
            "expected": c2_expected,
            "actual": placements,
            "passed": placements == c2_expected,
        })

        # Case 3: uninitialized trigger does not create BS5 tooltip
        page.hover("#tip-uninit")
        c3_actual = page.evaluate("""() => ({
            tooltip_count: document.querySelectorAll('.tooltip.show').length,
            native_title_intact: document.querySelector('#tip-uninit').getAttribute('title'),
        })""")
        c3_expected = {"tooltip_count": 0, "native_title_intact": "未初始化按钮"}
        cases.append({
            "name": "tooltip_uninitialized_guard",
            "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.Tooltip 批量初始化与 title 迁移、默认上方弹出与移出销毁、top/bottom/left/right 四方位几何校验以及未初始化控件不触发。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:Bootstrap5

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

下载课程关联工程包:Bootstrap5

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

Bootstrap 5 将 Tooltip 设为按需启用(opt-in)组件,必须在 JavaScript 中选取 `[data-bs-toggle="tooltip"]` 并逐个调用 `new bootstrap.Tooltip(el)` 初始化,否则浏览器只会显示默认原生 `title` 提示。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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