蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tooltip.py
explore-tooltip.py181 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/bootstrap5-tooltip-lab/explore-tooltip.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tooltip.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Bootstrap5

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

下载课程关联工程包:Bootstrap5

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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