蓝色天空网mbsky.com · 知识 · 实践 · 创造jQuery · 本地阅读预览
教程 / 前端开发 / jQuery

jQuery Tooltip

核验 jQuery UI Tooltip 部件如何接管并替换原生 title 工具提示框、表单控件聚焦辅助说明以及自定义内容与样式类配置。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

插件演进与替代原生 title 的核心机制

jQuery Tooltip 用于取代浏览器样式不可控的原生 `title` 工具提示,使开发者能够自由定制提示内容、定位与主题外观。早期独立版(1.3)已长期停止维护,官方明确推荐改用 jQuery UI 的工具提示框部件(Tooltip Widget),只需一行 `$(document).tooltip()` 即可为页面所有带 `title` 属性的元素统一接管自定义提示层。

文档链接、表单输入框与自定义样式实测

在典型页面中,普通超链接 `<a>` 与表单输入框 `<input id='age' title='...'>` 均可挂载工具提示:悬停或聚焦时,组件会将原 `title` 属性临时暂存并移除(防止同时弹出浏览器默认黄框),随后在目标元素附近插入带 `role='tooltip'` 的 `.ui-tooltip` 浮层;移出或失焦后销毁浮层并恢复 `title` 属性。本站离线 Chromium 实测验证:悬停 `#link-tip` 时原生 `title` 被移除且 `.ui-tooltip` 显示 `'That's what this widget is'`,移开鼠标后浮层归零且 `title` 完整恢复;聚焦 `#age` 输入框时浮层定位在输入框下方并显示统计说明文案;附加自定义 `content` 回调与 `tooltipClass: 'custom-tip'` 后,浮层正确呈现自定义内容与深蓝色背景 `rgb(15, 76, 129)`。

运行 jQuery Tooltip 接管原生 title、表单聚焦提示与自定义内容/样式类实验

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 在离线 Chromium 中通过 3 组用例:悬停链接时移除原生 title 并渲染 .ui-tooltip、移出后恢复 title 且移除浮层;聚焦 #age 输入框在控件下方弹出说明;自定义 content 与 tooltipClass 背景色 rgb(15, 76, 129) 准确生效。
运行 jQuery Tooltip 接管原生 title、表单聚焦提示与自定义内容/样式类实验

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

当前源码 SHA256:3eee3b463d0ef0e6ae4bdbc9c618af867a5acf198ed835c4e3614d82fed7af8b

下载本站示例源码

本地运行

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

下载jQuery Tooltip实验

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

ZIP SHA256:772a5bf224d7f79216a0a1de00d83805fe2285a67bc2739eb79f2b4f8a8067bf

常见错误与边界

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

练习与解答

自定义 Tooltip 在鼠标悬停期间为什么要临时移除目标元素的原生 title 属性,并在移开后恢复?

展开参考解答

如果不移除原生 title,浏览器会在几百毫秒后同时绘制系统自带提示框,造成双层提示重叠遮挡;移出时恢复 title 则确保辅助技术与后续脚本仍能读取原始属性。

规范与官方依据