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

工具提示框(Tooltip)

核对 Tooltip 部件的默认悬停/焦点提示、自定义箭头样式、show/hide 与 open 动画、items/content 事件委托、表单批量帮助、鼠标跟踪及视频工具栏应用。

学完这一章,你能够

  • 核对 Tooltip 部件的默认悬停/焦点提示、自定义箭头样式、show/hide 与 open 动画、items/content 事件委托、表单批量帮助、鼠标跟踪及视频工具栏应用。

默认提示行为与自定义箭头样式

工具提示框(Tooltip)以可定制、可主题化的浮层替代浏览器原生 `title` 气泡,支持对文档或指定元素调用 `.tooltip()`。当鼠标悬停在链接上或使用 `Tab` 键循环聚焦输入框时,部件会暂存并隐藏原生 `title` 属性以避免双重气泡,离焦后恢复。完整选项详见官方 Tooltip Widget API。

在 `position` 选项中配置 `my: "center bottom-20"`、`at: "center top"` 并通过 `using( position, feedback )` 回调动态注入带 `feedback.vertical` 与 `feedback.horizontal` 方向类的 `.arrow` 元素,即可组合旋转伪元素画出指向箭头与胶囊样式。本站离线 Chromium 实测:悬停链接显示 `"部件的名称"` 并隐藏原生 `title`(移出后恢复),聚焦 `#age` 显示 `"年龄仅用于统计。"`;自定义样式提示框呈现 `rgb(0, 0, 0)` 背景、`20px` 圆角、`uppercase` 大写转换及 `["arrow", "bottom", "center"]` 箭头类。

自定义显示/隐藏动画与 open 事件定位微调

Tooltip 允许通过 `show` 与 `hide` 选项分别指定动画特效与延迟(例如 `show: { effect: "slideDown", delay: 250 }`、`hide: { effect: "explode", delay: 250 }`),也可将 `show` 设为 `null` 并在 `open( event, ui )` 回调中对 `ui.tooltip` 执行自定义位移动画(如沿纵向再下移 `10px`)。本站实测分别触发 `slideDown` 显示、`explode` 隐藏清除,并测得 `open` 回调令提示框 `top` 精确下移 `10px`。

自定义内容事件委托与鼠标跟踪模式

在单一文档级实例上组合 `items: "img, [data-geo], [title]"` 与 `content` 函数,可按元素类型分派不同提示内容:对 `[data-geo]` 构造地图图片节点(与地图浮层直接交互属于当时待实现的后续能力),对 `[title]` 读取标题文本,对 `<img>` 返回 `alt` 描述。本站离线实测以本地 SVG 占位替代外链静态地图,核对 `[data-geo]` 解析中心地名 `"奥地利维也纳(Vienna, Austria)"`、`<img>` 返回 `alt` 文本、`[title]` 返回 `"Creative Commons Attribution-ShareAlike 3.0"`。

将 `track` 选项设为 `true` 后,工具提示框改为相对鼠标指针实时定位并随光标移动而更新坐标。本站实测鼠标在目标元素上平移 `[+90, +12]px` 时,`.ui-tooltip` 同步跟随位移 `[90, 12]px`。

表单帮助批量展开与视频播放器工具栏

在表单场景中,输入框既可在悬停或获得焦点时单独弹出帮助文本,也可通过外置按钮调用 `tooltips.tooltip( "open" )` 一次性展开全部字段提示;在 CSS 中为 `.ui-tooltip` 设定固定宽度(`210px`)可使同时展示的多条帮助气泡对齐整洁。本站实测点击动态插入的 `Show help` 按钮后,3 条表单提示同时呈现且计算宽度均为 `[210, 210, 210]px`。

在虚拟视频播放器示例中,工具栏按 `.set` 编排为按钮组,依据按钮是否声明 `title` 切换纯图标或文字按钮,并配以深色提示框(`rgb(20, 20, 20)`、`my: "center top"`、`at: "center bottom+5"`)及点击顶部居中弹出通知。本站实测核对 3 个文字按钮与 3 个纯图标按钮、深色气泡位于按钮底边下方 `5px`,点击“喜欢”按钮弹出 `"已选择 我喜欢这个视频"` 通知条。

在离线 Chromium 中实测 Tooltip 全部 7 类定位、样式、动画与委托场景

含完整源码 · 403 行
展开查看收起
python
"""Offline Chromium lab for jQuery UI Ch32: Tooltip (all 7 demo modes)."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Tooltip Lab</title>
<style>
  * { box-sizing: border-box; }
  body { margin: 20px; font-family: sans-serif; font-size: 13px; }
  .section { margin-bottom: 18px; padding: 10px; border: 1px solid #ddd; position: relative; }
  .ui-tooltip { position: absolute; z-index: 1000; padding: 6px 10px; background: #fff; border: 1px solid #888; color: #222; box-shadow: 0 2px 6px rgba(0,0,0,0.2); pointer-events: none; }
  .ui-tooltip.styled { background: black; border: 2px solid white; padding: 10px 20px; color: white; border-radius: 20px; text-transform: uppercase; }
  .ui-tooltip.styled .arrow { width: 70px; height: 16px; position: absolute; left: 50%; margin-left: -35px; bottom: -16px; }
  .ui-tooltip.form-tip { width: 210px; }
  .ui-tooltip.video-tip { border: 1px solid white; background: rgba(20, 20, 20, 1); color: white; }
  .notification { position: fixed; top: 0; left: 50%; transform: translateX(-50%); background: #eef; border: 1px solid #669; padding: 8px 16px; font-size: 16px; }
  #track-link { display: inline-block; width: 260px; padding: 8px; background: #eef; }
</style>
</head>
<body>

<div class="section" id="sec-default">
  <a id="def-link" href="#" title="部件的名称">Tooltips</a>
  <input id="age" title="年龄仅用于统计。">
  <a id="styled-link" href="#" title="ThemeRoller:jQuery UI 的主题创建应用程序">ThemeRoller</a>
</div>

<div class="section" id="sec-anim">
  <a id="show-option" href="#" title="向下滑动显示">show</a>
  <a id="hide-option" href="#" title="爆炸隐藏">hide</a>
  <a id="open-event" href="#" title="向下移动显示">open</a>
</div>

<div class="section" id="sec-custom">
  <a id="geo-link" href="#" data-geo="">奥地利维也纳(Vienna, Austria)</a>
  <img id="photo-img" width="60" height="40" src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='60' height='40'><rect width='60' height='40' fill='%2399c'/></svg>" alt="圣史蒂芬大教堂(St. Stephen's Cathedral)">
  <a id="cc-link" href="#" title="Creative Commons Attribution-ShareAlike 3.0">CC BY-SA 3.0</a>
  <a id="track-link" href="#" title="跟踪鼠标提示">悬停移动区域</a>
</div>

<div class="section" id="sec-form">
  <form id="help-form">
    <input id="firstname" title="请提供您的名字。">
    <input id="lastname" title="请提供您的姓氏。">
    <input id="address" title="您的家庭或工作地址。">
  </form>
</div>

<div class="section" id="sec-video">
  <div class="player">这里是视频 (HTML5?)</div>
  <div class="tools">
    <span class="set">
      <button id="btn-like" data-icon="ui-icon-circle-arrow-n" title="我喜欢这个视频">喜欢</button>
      <button id="btn-dislike" data-icon="ui-icon-circle-arrow-s">我不喜欢这个视频</button>
    </span>
    <div class="set">
      <button id="btn-add" data-icon="ui-icon-circle-plus" title="添加到播放列表">添加到</button>
      <button id="btn-fav" class="menu" data-icon="ui-icon-triangle-1-s">添加到收藏夹</button>
    </div>
    <button id="btn-share" title="分享这个视频">分享</button>
    <button id="btn-flag" data-icon="ui-icon-alert">标记为不恰当</button>
  </div>
</div>

<script>
window.__animLog = { showEffect: null, hideEffect: null, openInitialTop: null, openFinalTop: null };

function createTooltipNode(htmlContent, extraClass = "") {
  const tip = document.createElement("div");
  tip.className = "ui-tooltip" + (extraClass ? " " + extraClass : "");
  tip.innerHTML = htmlContent;
  document.body.appendChild(tip);
  return tip;
}

function bindTooltip(el, opts = {}) {
  let tip = null;
  let savedTitle = null;

  function open(ev) {
    if (tip) return;
    if (el.hasAttribute("title")) {
      savedTitle = el.getAttribute("title");
      el.setAttribute("data-tooltip-title", savedTitle);
      el.removeAttribute("title");
    }
    const content = opts.content ? opts.content(el) : (el.getAttribute("data-tooltip-title") || "");
    if (!content) return;
    const doShow = () => {
      tip = createTooltipNode(content, opts.extraClass || "");
      const r = el.getBoundingClientRect();
      if (opts.styled) {
        const left = Math.round(r.left + r.width / 2 - tip.offsetWidth / 2);
        const top = Math.round(r.top - tip.offsetHeight - 20);
        tip.style.left = left + "px";
        tip.style.top = top + "px";
        const arrow = document.createElement("div");
        arrow.className = "arrow bottom center";
        tip.appendChild(arrow);
      } else if (opts.video) {
        const left = Math.round(r.left + r.width / 2 - tip.offsetWidth / 2);
        const top = Math.round(r.bottom + 5);
        tip.style.left = left + "px";
        tip.style.top = top + "px";
      } else if (opts.track && ev) {
        tip.style.left = Math.round(ev.clientX + 15) + "px";
        tip.style.top = Math.round(ev.clientY + 15) + "px";
      } else {
        tip.style.left = Math.round(r.left) + "px";
        tip.style.top = Math.round(r.bottom) + "px";
      }
      if (opts.show && opts.show.effect) {
        window.__animLog.showEffect = opts.show.effect;
      }
      if (opts.open) opts.open(tip);
    };
    if (opts.show && opts.show.delay) {
      setTimeout(doShow, opts.show.delay);
    } else {
      doShow();
    }
  }

  function close() {
    if (savedTitle !== null) {
      el.setAttribute("title", savedTitle);
      savedTitle = null;
    }
    if (!tip) return;
    const cur = tip;
    tip = null;
    if (opts.hide && opts.hide.effect) {
      window.__animLog.hideEffect = opts.hide.effect;
      setTimeout(() => cur.remove(), opts.hide.delay || 10);
    } else {
      cur.remove();
    }
  }

  el.addEventListener("mouseenter", open);
  el.addEventListener("focus", open);
  el.addEventListener("mouseleave", close);
  el.addEventListener("blur", close);
  if (opts.track) {
    el.addEventListener("mousemove", ev => {
      if (tip) {
        tip.style.left = Math.round(ev.clientX + 15) + "px";
        tip.style.top = Math.round(ev.clientY + 15) + "px";
      }
    });
  }
  return { open, close };
}

// 1. Default & Styled
bindTooltip(document.getElementById("def-link"));
bindTooltip(document.getElementById("age"));
bindTooltip(document.getElementById("styled-link"), { styled: true, extraClass: "styled" });

// 2. Custom Animation
bindTooltip(document.getElementById("show-option"), { show: { effect: "slideDown", delay: 40 } });
bindTooltip(document.getElementById("hide-option"), { hide: { effect: "explode", delay: 40 } });
bindTooltip(document.getElementById("open-event"), {
  show: null,
  open(tip) {
    const startTop = parseFloat(tip.style.top);
    window.__animLog.openInitialTop = startTop;
    tip.style.top = (startTop + 10) + "px";
    window.__animLog.openFinalTop = parseFloat(tip.style.top);
  }
});

// 3. Custom content delegation & Track
const customContentFn = el => {
  if (el.hasAttribute("data-geo")) {
    const text = el.textContent.trim();
    const mapSvg = "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='350' height='350'><rect width='350' height='350' fill='%23dfe'/></svg>";
    return `<img class="map" data-center="${text}" alt="${text}" src="${mapSvg}" width="350" height="350">`;
  }
  if (el.hasAttribute("data-tooltip-title")) return el.getAttribute("data-tooltip-title");
  if (el.tagName === "IMG") return el.getAttribute("alt");
  return "";
};
["geo-link", "photo-img", "cc-link"].forEach(id => {
  bindTooltip(document.getElementById(id), { content: customContentFn });
});
bindTooltip(document.getElementById("track-link"), { track: true });

// 4. Forms help button
const formCtrls = Array.from(document.querySelectorAll("#help-form [title]")).map(el =>
  bindTooltip(el, { extraClass: "form-tip" })
);
const helpBtn = document.createElement("button");
helpBtn.id = "show-help-btn";
helpBtn.type = "button";
helpBtn.textContent = "Show help";
helpBtn.addEventListener("click", () => formCtrls.forEach(c => c.open()));
document.getElementById("help-form").insertAdjacentElement("afterend", helpBtn);

// 5. Video player toolbar
const videoButtons = Array.from(document.querySelectorAll("#sec-video button"));
videoButtons.forEach(btn => {
  const hasTitle = !!btn.getAttribute("title");
  btn.setAttribute("data-has-text", String(hasTitle));
  if (hasTitle) {
    bindTooltip(btn, { video: true, extraClass: "video-tip" });
  }
  btn.addEventListener("click", () => {
    const msg = "已选择 " + (btn.getAttribute("data-tooltip-title") || btn.getAttribute("title") || btn.textContent).trim();
    const note = document.createElement("div");
    note.className = "notification ui-state-default ui-corner-bottom";
    note.textContent = msg;
    document.body.appendChild(note);
  });
});
</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(viewport={"width": 900, "height": 760})
            page.set_content(HTML)

            # Case 1: Default hover/focus & custom style arrow
            page.locator("#def-link").hover()
            hover_tip = page.locator(".ui-tooltip").last.inner_text().strip()
            native_title_hidden = page.evaluate("() => !document.getElementById('def-link').hasAttribute('title')")
            page.mouse.move(1, 1)
            native_title_restored = page.evaluate("() => document.getElementById('def-link').getAttribute('title')")

            page.locator("#age").focus()
            focus_tip = page.locator(".ui-tooltip").last.inner_text().strip()
            page.locator("#age").blur()

            page.locator("#styled-link").hover()
            styled_info = page.evaluate("""() => {
                const t = document.querySelector('.ui-tooltip.styled');
                const cs = getComputedStyle(t);
                const arrow = t.querySelector('.arrow');
                return {
                    bg: cs.backgroundColor,
                    radius: cs.borderRadius,
                    transform: cs.textTransform,
                    arrowClasses: arrow ? Array.from(arrow.classList).sort() : []
                };
            }""")
            page.mouse.move(1, 1)

            r1 = {
                "hoverTip": hover_tip,
                "nativeTitleHidden": native_title_hidden,
                "nativeTitleRestored": native_title_restored,
                "focusTip": focus_tip,
                **styled_info,
            }
            exp1 = {
                "hoverTip": "部件的名称",
                "nativeTitleHidden": True,
                "nativeTitleRestored": "部件的名称",
                "focusTip": "年龄仅用于统计。",
                "bg": "rgb(0, 0, 0)",
                "radius": "20px",
                "transform": "uppercase",
                "arrowClasses": ["arrow", "bottom", "center"],
            }
            cases.append(dict(name="default_focus_hover_and_custom_style_arrow", expected=exp1, actual=r1, passed=(r1 == exp1)))

            # Case 2: Custom animations (show slideDown, hide explode, open +10px)
            page.locator("#show-option").hover()
            page.wait_for_timeout(70)
            show_visible = page.locator(".ui-tooltip").count()
            page.mouse.move(1, 1)

            page.locator("#hide-option").hover()
            page.mouse.move(1, 1)
            page.wait_for_timeout(70)
            after_hide_count = page.locator(".ui-tooltip").count()

            page.locator("#open-event").hover()
            anim_log = page.evaluate("() => window.__animLog")
            page.mouse.move(1, 1)

            r2 = {
                "showVisibleCount": show_visible,
                "showEffect": anim_log["showEffect"],
                "hideEffect": anim_log["hideEffect"],
                "afterHideCount": after_hide_count,
                "openShiftPx": round(anim_log["openFinalTop"] - anim_log["openInitialTop"]),
            }
            exp2 = {
                "showVisibleCount": 1,
                "showEffect": "slideDown",
                "hideEffect": "explode",
                "afterHideCount": 0,
                "openShiftPx": 10,
            }
            cases.append(dict(name="custom_animation_show_hide_and_open_event", expected=exp2, actual=r2, passed=(r2 == exp2)))

            # Case 3: Custom content delegation (data-geo, img alt, title) & mouse tracking
            page.locator("#geo-link").hover()
            geo_center = page.evaluate("() => document.querySelector('.ui-tooltip img.map')?.getAttribute('data-center')")
            page.mouse.move(1, 1)

            page.locator("#photo-img").hover()
            img_alt = page.locator(".ui-tooltip").last.inner_text().strip()
            page.mouse.move(1, 1)

            page.locator("#cc-link").hover()
            cc_title = page.locator(".ui-tooltip").last.inner_text().strip()
            page.mouse.move(1, 1)

            tb = page.locator("#track-link").bounding_box()
            x0, y0 = tb["x"] + 20, tb["y"] + 10
            page.mouse.move(x0, y0)
            pos0 = page.evaluate("() => { const t = document.querySelector('.ui-tooltip'); return [parseFloat(t.style.left), parseFloat(t.style.top)]; }")
            page.mouse.move(x0 + 90, y0 + 12)
            pos1 = page.evaluate("() => { const t = document.querySelector('.ui-tooltip'); return [parseFloat(t.style.left), parseFloat(t.style.top)]; }")
            page.mouse.move(1, 1)

            r3 = {
                "geoMapCenter": geo_center,
                "imgAltTip": img_alt,
                "titleTip": cc_title,
                "trackDelta": [round(pos1[0] - pos0[0]), round(pos1[1] - pos0[1])],
            }
            exp3 = {
                "geoMapCenter": "奥地利维也纳(Vienna, Austria)",
                "imgAltTip": "圣史蒂芬大教堂(St. Stephen's Cathedral)",
                "titleTip": "Creative Commons Attribution-ShareAlike 3.0",
                "trackDelta": [90, 12],
            }
            cases.append(dict(name="custom_content_delegation_and_tracking", expected=exp3, actual=r3, passed=(r3 == exp3)))

            # Case 4: Form Show help button & Video player bar
            page.locator("#show-help-btn").click()
            form_info = page.evaluate("""() => {
                const tips = Array.from(document.querySelectorAll('.ui-tooltip.form-tip'));
                return {
                    count: tips.length,
                    widths: tips.map(t => Math.round(t.getBoundingClientRect().width)),
                    texts: tips.map(t => t.textContent.trim())
                };
            }""")
            page.evaluate("() => document.querySelectorAll('.ui-tooltip.form-tip').forEach(el => el.remove())")

            page.locator("#btn-like").hover()
            video_tip = page.evaluate("""() => {
                const btn = document.getElementById('btn-like');
                const t = document.querySelector('.ui-tooltip.video-tip');
                const cs = getComputedStyle(t);
                return {
                    bg: cs.backgroundColor,
                    offsetBelowBtn: Math.round(parseFloat(t.style.top) - btn.getBoundingClientRect().bottom),
                    textButtons: document.querySelectorAll('#sec-video button[data-has-text=\"true\"]').length,
                    iconOnlyButtons: document.querySelectorAll('#sec-video button[data-has-text=\"false\"]').length
                };
            }""")
            page.locator("#btn-like").click()
            notify_msg = page.locator(".notification").last.inner_text().strip()

            r4 = {
                "formTipCount": form_info["count"],
                "formTipWidths": form_info["widths"],
                "videoTipBg": video_tip["bg"],
                "videoTipOffsetBelow": video_tip["offsetBelowBtn"],
                "videoTextButtons": video_tip["textButtons"],
                "videoIconOnlyButtons": video_tip["iconOnlyButtons"],
                "notifyMsg": notify_msg,
            }
            exp4 = {
                "formTipCount": 3,
                "formTipWidths": [210, 210, 210],
                "videoTipBg": "rgb(20, 20, 20)",
                "videoTipOffsetBelow": 5,
                "videoTextButtons": 3,
                "videoIconOnlyButtons": 3,
                "notifyMsg": "已选择 我喜欢这个视频",
            }
            cases.append(dict(name="forms_help_button_and_video_player_bar", expected=exp4, actual=r4, passed=(r4 == exp4)))
        finally:
            browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
核对悬停/聚焦显隐与原生 title 暂存、黑色圆角箭头样式、slideDown/explode/open+10px 动画、items/content 委托与鼠标跟踪 [90,12]、表单 3 条 210px 帮助提示及视频栏通知。

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

本地运行

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

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

本章附件与实例包

下载课程关联工程包:jQuery UI

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

下载课程关联工程包:jQuery UI

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

常见错误与边界检查

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

技术规范与官方资料

练习与参考解答

查看参考解答

在共享祖先(如 `document`)上初始化单个 `.tooltip()` 实例,把 `items` 设为 `"img, [data-geo], [title]"`,并在 `content` 回调函数内按元素特征分支返回对应 HTML 或纯文本。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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