蓝色天空.知识 · 实践 · 创造
我的收藏
jQuery 教程目录 40章
jQuery / LEARN BY DOING

jQuery Tooltip

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

学完这一章,你能够

  • 核验 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、表单聚焦提示与自定义内容/样式类实验

含完整源码 · 196 行
展开查看收起
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) 准确生效。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

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

下载本章实验包 (mbskycom202612a903.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:jQuery

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

下载课程关联工程包:jQuery

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

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

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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