Bootstrap4 提示框
核对 Bootstrap 4 提示框(Tooltip)的手动初始化要求、悬停显隐与默认上方定位、四方向 `data-placement`、`data-html="true"` 富文本及禁用按钮包裹方案。
学完这一章,你能够
- 核对 Bootstrap 4 提示框(Tooltip)的手动初始化要求、悬停显隐与默认上方定位、四方向 `data-placement`、`data-html="true"` 富文本及禁用按钮包裹方案。
创建提示框与显式初始化机制
提示框(Tooltip)是在鼠标移入元素时浮现、移出后自动消失的轻量气泡,通过给目标元素添加 `data-toggle="tooltip"` 并将提示文本写入 `title` 属性来定义。出于性能考虑,Bootstrap 4 不会自动扫描激活提示框,必须在页面就绪的 jQuery 初始化代码中手动调用 `$('[data-toggle="tooltip"]').tooltip()`。本站离线 Chromium 实测:初始化后原生 `title` 被移至 `data-original-title` 以避免与浏览器原生黄框重叠;鼠标移入后动态挂载 `.tooltip.show`(`z-index: 1070`、`opacity: 0.9`),默认定位在元素正上方(提示框底边不高于触发元素顶边),鼠标移离后 DOM 节点立即卸载清零。
四方向定位、HTML 内容与禁用按钮处理
提示框默认显示在元素上方,可通过 `data-placement` 指定 `top`、`bottom`、`left` 或 `right`,同时适用于链接 `<a>` 与按钮 `<button>`。本站实测四个方向的按钮在悬停时生成的提示框边界均严格落在目标元素的对应方位侧(上/下/左/右四项坐标校验全为 `true`)。
若需要在提示内容中渲染加粗、斜体或下划线等 HTML 标签,应设置 `data-html="true"` 并在 `title` 中编写标签(生产环境需确保内容受信任以防 XSS):实测开启 `data-html="true"` 后 `.tooltip-inner` 解析出 `["EM", "U", "B"]` 子节点,而 `data-html="false"` 时标签被按纯文本 `"<b>Escaped</b>"` 原样转义。针对 `disabled` 按钮(原生禁用按钮不触发鼠标事件),标准做法是在外层包裹 `<span class="d-inline-block" tabindex="0" data-toggle="tooltip">` 并给内部禁用按钮设置 `pointer-events: none`;实测悬停外层包裹元素可稳定弹出 `"Disabled tooltip"` 提示。
离线 Chromium 实测提示框初始化、四方向定位、HTML 解析与禁用按钮包裹触发
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
浏览器默认抑制 `disabled` 表单控件的鼠标与键盘焦点事件,直接绑定提示框无法触发;外层 `<span>` 配合 `tabindex="0"` 接管悬停与键盘聚焦,而 `pointer-events: none` 确保鼠标事件穿透禁用按钮直达外层容器。