"""Offline Playwright Chromium lab for jQuery Ch 39: plugin-tooltip (jQuery UI Tooltip replacement)."""
import json
from playwright.sync_api import sync_playwright
HTML_DOC = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery Tooltip 离线实验</title>
<style>
label { display: inline-block; width: 5em; }
.ui-tooltip {
position: absolute;
padding: 6px 10px;
background: rgb(51, 51, 51);
color: rgb(255, 255, 255);
border: 1px solid rgb(17, 17, 17);
border-radius: 4px;
font-size: 12px;
pointer-events: none;
}
.custom-tip {
background: rgb(15, 76, 129);
}
</style>
</head>
<body>
<p><a id="link-tip" href="#" title="That's what this widget is">Tooltips</a> can be attached to any element.</p>
<p><label for="age">Your age:</label><input id="age" title="We ask for your age only for statistical purposes."></p>
<p><button id="custom-btn" data-hint="Rendered via content callback">Custom Tip</button></p>
<script>
function attachTooltip(root, opts = {}) {
let activeTip = null;
let activeTarget = null;
function openTip(target) {
closeTip();
const rawTitle = target.getAttribute('title');
const content = typeof opts.content === 'function' ? opts.content.call(target) : rawTitle;
if (!content) return;
if (rawTitle !== null) {
target.dataset.uiTooltipTitle = rawTitle;
target.removeAttribute('title');
}
const tip = document.createElement('div');
tip.className = 'ui-tooltip' + (opts.tooltipClass ? ' ' + opts.tooltipClass : '');
tip.setAttribute('role', 'tooltip');
tip.textContent = content;
const rect = target.getBoundingClientRect();
tip.style.left = Math.round(rect.left) + 'px';
tip.style.top = Math.round(rect.bottom + 6) + 'px';
document.body.appendChild(tip);
activeTip = tip;
activeTarget = target;
}
function closeTip() {
if (activeTarget && activeTarget.dataset.uiTooltipTitle !== undefined) {
activeTarget.setAttribute('title', activeTarget.dataset.uiTooltipTitle);
delete activeTarget.dataset.uiTooltipTitle;
}
if (activeTip && activeTip.parentNode) activeTip.parentNode.removeChild(activeTip);
activeTip = null;
activeTarget = null;
}
const selector = opts.items || '[title]';
root.addEventListener('mouseover', (ev) => {
const t = ev.target.closest(selector);
if (t) openTip(t);
});
root.addEventListener('mouseout', (ev) => {
if (activeTarget && (ev.target === activeTarget || activeTarget.contains(ev.target))) closeTip();
});
root.addEventListener('focusin', (ev) => {
const t = ev.target.closest(selector);
if (t) openTip(t);
});
root.addEventListener('focusout', (ev) => {
if (activeTarget && (ev.target === activeTarget || activeTarget.contains(ev.target))) closeTip();
});
}
attachTooltip(document);
attachTooltip(document.getElementById('custom-btn'), {
items: '#custom-btn',
tooltipClass: 'custom-tip',
content() { return this.getAttribute('data-hint'); },
});
</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)
try:
page = browser.new_page()
page.set_content(HTML_DOC, wait_until="load")
# Case 1: Hover replaces native title with .ui-tooltip and restores title on mouseout
page.hover("#link-tip")
on_hover = page.evaluate("""() => ({
tipText: document.querySelector('.ui-tooltip')?.textContent || '',
tipRole: document.querySelector('.ui-tooltip')?.getAttribute('role') || '',
nativeTitleRemoved: !document.getElementById('link-tip').hasAttribute('title'),
})""")
page.mouse.move(1, 1)
after_leave = page.evaluate("""() => ({
tipCount: document.querySelectorAll('.ui-tooltip').length,
restoredTitle: document.getElementById('link-tip').getAttribute('title'),
})""")
res1 = {"on_hover": on_hover, "after_leave": after_leave}
exp1 = {
"on_hover": {
"tipText": "That's what this widget is",
"tipRole": "tooltip",
"nativeTitleRemoved": True,
},
"after_leave": {
"tipCount": 0,
"restoredTitle": "That's what this widget is",
},
}
cases.append(dict(
name="hover_replaces_native_title",
expected=exp1,
actual=res1,
passed=(res1 == exp1),
))
# Case 2: Form input focus displays contextual tooltip positioned below input
page.focus("#age")
res2 = page.evaluate("""() => {
const inp = document.getElementById('age').getBoundingClientRect();
const tip = document.querySelector('.ui-tooltip');
const tRect = tip.getBoundingClientRect();
return {
tipText: tip.textContent,
positionedBelow: tRect.top >= Math.floor(inp.bottom),
bg: getComputedStyle(tip).backgroundColor,
};
}""")
exp2 = {
"tipText": "We ask for your age only for statistical purposes.",
"positionedBelow": True,
"bg": "rgb(51, 51, 51)",
}
cases.append(dict(
name="form_input_focus_and_hover_tooltip",
expected=exp2,
actual=res2,
passed=(res2 == exp2),
))
# Case 3: Custom content callback and tooltipClass style
page.hover("#custom-btn")
res3 = page.evaluate("""() => {
const tip = document.querySelector('.ui-tooltip.custom-tip');
return {
tipText: tip ? tip.textContent : '',
bg: tip ? getComputedStyle(tip).backgroundColor : '',
hasCustomClass: Boolean(tip && tip.classList.contains('custom-tip')),
};
}""")
exp3 = {
"tipText": "Rendered via content callback",
"bg": "rgb(15, 76, 129)",
"hasCustomClass": True,
}
cases.append(dict(
name="custom_content_and_style_classes",
expected=exp3,
actual=res3,
passed=(res3 == exp3),
))
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/jquery-plugin-tooltip-lab/explore-plugin-tooltip.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-plugin-tooltip.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a903.zip
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip