蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-example-tooltip.py
explore-example-tooltip.py403 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/jqueryui-example-tooltip-lab/explore-example-tooltip.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-example-tooltip.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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