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

离线 Chromium 实测提示框初始化、四方向定位、HTML 解析与禁用按钮包裹触发

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tooltip.py
explore-tooltip.py211 行
"""Offline Playwright Chromium lab for Bootstrap 4 Chapter 29 (tooltip)."""
import json
from playwright.sync_api import sync_playwright

BS4_TOOLTIP_CSS = """
* { box-sizing: border-box; }
body { margin: 0; padding: 120px 180px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; font-size: 16px; }
.row { display: flex; gap: 36px; margin-bottom: 60px; align-items: center; }
.d-inline-block { display: inline-block; }
.btn { padding: 0.375rem 0.75rem; font-size: 1rem; border: 1px solid #6c757d; border-radius: 0.25rem; background: #6c757d; color: #fff; }
.tooltip {
  position: fixed; z-index: 1070; display: block; font-size: 0.875rem; opacity: 0.9; pointer-events: none;
}
.tooltip-inner {
  max-width: 200px; padding: 0.25rem 0.5rem; color: #fff; text-align: center;
  background-color: #000; border-radius: 0.25rem;
}
"""

BS4_TOOLTIP_JS = """
function initTooltips() {
  document.querySelectorAll('[data-toggle="tooltip"]').forEach(el => {
    const title = el.getAttribute('title') || '';
    el.setAttribute('data-original-title', title);
    el.removeAttribute('title');
    let tip = null;
    function show() {
      if (tip) return;
      const placement = el.getAttribute('data-placement') || 'top';
      const allowHtml = el.getAttribute('data-html') === 'true';
      tip = document.createElement('div');
      tip.className = 'tooltip bs-tooltip-' + placement + ' show';
      tip.setAttribute('role', 'tooltip');
      const inner = document.createElement('div');
      inner.className = 'tooltip-inner';
      if (allowHtml) inner.innerHTML = el.getAttribute('data-original-title');
      else inner.textContent = el.getAttribute('data-original-title');
      tip.appendChild(inner);
      document.body.appendChild(tip);
      const r = el.getBoundingClientRect();
      const tr = tip.getBoundingClientRect();
      const gap = 8;
      let left = r.left + (r.width - tr.width) / 2;
      let top = r.top - tr.height - gap;
      if (placement === 'bottom') top = r.bottom + gap;
      if (placement === 'left') { left = r.left - tr.width - gap; top = r.top + (r.height - tr.height) / 2; }
      if (placement === 'right') { left = r.right + gap; top = r.top + (r.height - tr.height) / 2; }
      tip.style.left = Math.round(left) + 'px';
      tip.style.top = Math.round(top) + 'px';
    }
    function hide() {
      if (tip) { tip.remove(); tip = null; }
    }
    el.addEventListener('mouseenter', show);
    el.addEventListener('mouseleave', hide);
    el.addEventListener('focus', show);
    el.addEventListener('blur', hide);
  });
}
initTooltips();
"""


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


def run():
    cases = []
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page(viewport={"width": 1000, "height": 700})
        page.set_content(f"""<!DOCTYPE html><html><head><style>{BS4_TOOLTIP_CSS}</style></head><body>
        <div class="row">
          <a id="t-basic" href="#" data-toggle="tooltip" title="我是提示内容!">鼠标移动到我这</a>
        </div>
        <div class="row">
          <button id="b-top" type="button" class="btn" data-toggle="tooltip" data-placement="top" title="Tooltip on top">Top</button>
          <button id="b-bottom" type="button" class="btn" data-toggle="tooltip" data-placement="bottom" title="Tooltip on bottom">Bottom</button>
          <button id="b-left" type="button" class="btn" data-toggle="tooltip" data-placement="left" title="Tooltip on left">Left</button>
          <button id="b-right" type="button" class="btn" data-toggle="tooltip" data-placement="right" title="Tooltip on right">Right</button>
        </div>
        <div class="row">
          <button id="b-html" type="button" class="btn" data-toggle="tooltip" data-html="true" title="<em>Tooltip</em> <u>with</u> <b>HTML</b>">HTML Tip</button>
          <button id="b-plain" type="button" class="btn" data-toggle="tooltip" data-html="false" title="<b>Escaped</b>">Plain Tip</button>
          <span id="dis-wrap" class="d-inline-block" tabindex="0" data-toggle="tooltip" title="Disabled tooltip">
            <button id="dis-btn" class="btn" style="pointer-events: none;" type="button" disabled>Disabled button</button>
          </span>
        </div>
        <script>{BS4_TOOLTIP_JS}</script></body></html>""")

        # Case 1: init title handoff, hover show, mouseleave hide
        init_state = page.evaluate("""() => ({
          count: document.querySelectorAll('.tooltip').length,
          hasNativeTitle: document.querySelector('#t-basic').hasAttribute('title'),
          originalTitle: document.querySelector('#t-basic').getAttribute('data-original-title'),
        })""")
        page.hover("#t-basic")
        hover_state = page.evaluate("""() => {
          const tip = document.querySelector('.tooltip');
          const tr = tip.getBoundingClientRect();
          const er = document.querySelector('#t-basic').getBoundingClientRect();
          return {
            count: document.querySelectorAll('.tooltip').length,
            text: tip.querySelector('.tooltip-inner').textContent,
            zIndex: getComputedStyle(tip).zIndex,
            opacity: getComputedStyle(tip).opacity,
            aboveTrigger: tr.bottom <= er.top,
          };
        }""")
        page.mouse.move(10, 10)
        after_leave = page.evaluate("() => document.querySelectorAll('.tooltip').length")
        actual1 = {
            "init_count": init_state["count"],
            "native_title_cleared": not init_state["hasNativeTitle"],
            "data_original_title": init_state["originalTitle"],
            "hover_count": hover_state["count"],
            "hover_text": hover_state["text"],
            "hover_z_index": hover_state["zIndex"],
            "hover_opacity": hover_state["opacity"],
            "default_above_trigger": hover_state["aboveTrigger"],
            "after_leave_count": after_leave,
        }
        expected1 = {
            "init_count": 0,
            "native_title_cleared": True,
            "data_original_title": "我是提示内容!",
            "hover_count": 1,
            "hover_text": "我是提示内容!",
            "hover_z_index": "1070",
            "hover_opacity": "0.9",
            "default_above_trigger": True,
            "after_leave_count": 0,
        }
        cases.append(dict(
            name="tooltip_init_hover_and_hide",
            expected=expected1,
            actual=actual1,
            passed=(actual1 == expected1),
        ))

        # Case 2: 4 placements (top, bottom, left, right)
        placements = {}
        for side, sel in [("top", "#b-top"), ("bottom", "#b-bottom"), ("left", "#b-left"), ("right", "#b-right")]:
            page.hover(sel)
            ok = page.evaluate("""([side, sel]) => {
              const tip = document.querySelector('.tooltip').getBoundingClientRect();
              const el = document.querySelector(sel).getBoundingClientRect();
              if (side === 'top') return tip.bottom <= el.top;
              if (side === 'bottom') return tip.top >= el.bottom;
              if (side === 'left') return tip.right <= el.left;
              if (side === 'right') return tip.left >= el.right;
              return false;
            }""", [side, sel])
            placements[side] = ok
            page.mouse.move(10, 10)
        expected2 = {"top": True, "bottom": True, "left": True, "right": True}
        cases.append(dict(
            name="tooltip_four_placements_links_and_buttons",
            expected=expected2,
            actual=placements,
            passed=(placements == expected2),
        ))

        # Case 3: data-html="true" vs escaped text, and disabled button wrapper
        page.hover("#b-html")
        html_tags = page.evaluate("() => Array.from(document.querySelectorAll('.tooltip-inner *')).map(e => e.tagName)")
        page.mouse.move(10, 10)
        page.hover("#b-plain")
        plain_info = page.evaluate("""() => ({
          tags: Array.from(document.querySelectorAll('.tooltip-inner *')).map(e => e.tagName),
          text: document.querySelector('.tooltip-inner').textContent,
        })""")
        page.mouse.move(10, 10)
        page.hover("#dis-wrap")
        dis_info = page.evaluate("""() => ({
          inner_button_disabled: document.querySelector('#dis-btn').disabled,
          inner_button_pointer_events: getComputedStyle(document.querySelector('#dis-btn')).pointerEvents,
          wrapper_tooltip_text: document.querySelector('.tooltip-inner').textContent,
        })""")
        actual3 = {
            "html_true_child_tags": html_tags,
            "html_false_child_tags": plain_info["tags"],
            "html_false_literal_text": plain_info["text"],
            **dis_info,
        }
        expected3 = {
            "html_true_child_tags": ["EM", "U", "B"],
            "html_false_child_tags": [],
            "html_false_literal_text": "<b>Escaped</b>",
            "inner_button_disabled": True,
            "inner_button_pointer_events": "none",
            "wrapper_tooltip_text": "Disabled tooltip",
        }
        cases.append(dict(
            name="tooltip_html_and_disabled_wrapper",
            expected=expected3,
            actual=actual3,
            passed=(actual3 == expected3),
        ))

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


if __name__ == "__main__":
    run()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

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

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

下载课程关联工程包:Bootstrap4

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

下载课程关联工程包:Bootstrap4

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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