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

离线验证 Foundation 5 提示框悬停显隐、.has-tip 样式、四向定位与小屏通栏宽度

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tooltips.py
explore-tooltips.py190 行
"""Offline Playwright Chromium lab for Foundation Ch 27 (tooltips)."""
import json
from playwright.sync_api import sync_playwright

FOUNDATION_CSS = """
*, *::before, *::after { box-sizing: border-box; }
html, body { margin: 0; padding: 0; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 16px; color: #222; background: #fff; }
.stage { padding: 140px 220px; display: flex; flex-wrap: wrap; gap: 40px; align-items: center; }
.has-tip {
  border-bottom: 1px dotted #cccccc;
  color: #333333;
  cursor: help;
  font-weight: 700;
}
.tooltip {
  display: none;
  position: fixed;
  z-index: 1030;
  padding: 8px 10px;
  font-size: 14px;
  font-weight: 400;
  line-height: 1.3;
  background: #333333;
  color: #ffffff;
  border-radius: 0px;
  white-space: nowrap;
}
.tooltip.visible { display: block; }
.tooltip.radius { border-radius: 3px; }
.tooltip.round { border-radius: 1000px; }
@media only screen and (max-width: 40em) {
  .tooltip { left: 0 !important; width: 100% !important; white-space: normal; }
}
"""

TOOLTIP_JS = """
(function initTooltips() {
  document.querySelectorAll('[data-tooltip]').forEach((el, idx) => {
    const text = el.getAttribute('title') || '';
    el.setAttribute('data-tip-text', text);
    el.removeAttribute('title');
    const tip = document.createElement('span');
    tip.className = 'tooltip';
    tip.id = 'tip-' + el.id;
    if (el.classList.contains('radius')) tip.classList.add('radius');
    if (el.classList.contains('round')) tip.classList.add('round');
    tip.textContent = text;
    document.body.appendChild(tip);

    function positionTip() {
      tip.classList.add('visible');
      const tr = el.getBoundingClientRect();
      const pr = tip.getBoundingClientRect();
      const gap = 8;
      if (el.classList.contains('tip-top')) {
        tip.style.left = Math.round(tr.left) + 'px';
        tip.style.top = Math.round(tr.top - pr.height - gap) + 'px';
      } else if (el.classList.contains('tip-left')) {
        tip.style.left = Math.round(tr.left - pr.width - gap) + 'px';
        tip.style.top = Math.round(tr.top) + 'px';
      } else if (el.classList.contains('tip-right')) {
        tip.style.left = Math.round(tr.right + gap) + 'px';
        tip.style.top = Math.round(tr.top) + 'px';
      } else {
        tip.style.left = Math.round(tr.left) + 'px';
        tip.style.top = Math.round(tr.bottom + gap) + 'px';
      }
    }

    el.addEventListener('mouseenter', positionTip);
    el.addEventListener('mouseleave', () => tip.classList.remove('visible'));
  });
})();
"""

HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{FOUNDATION_CSS}</style></head>
<body>
  <div class="stage">
    <span id="plain" data-tooltip title="Hooray!">Hover over me!</span>
    <span id="hastip" data-tooltip class="has-tip" title="Hooray!">Hover over me!</span>
    <span id="t-top" data-tooltip class="has-tip tip-top" title="Top Tip">Top</span>
    <span id="t-bot" data-tooltip class="has-tip tip-bottom" title="Bottom Tip">Bottom</span>
    <span id="t-left" data-tooltip class="has-tip tip-left" title="Left Tip">Left</span>
    <span id="t-right" data-tooltip class="has-tip tip-right" title="Right Tip">Right</span>
    <span id="r-def" data-tooltip class="has-tip" title="Default">Default</span>
    <span id="r-rad" data-tooltip class="has-tip radius" title="Radius">Radius</span>
    <span id="r-rnd" data-tooltip class="has-tip round" title="Round">Round</span>
  </div>
  <script>{TOOLTIP_JS}</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)
        page = browser.new_page(viewport={"width": 900, "height": 500})
        page.set_content(HTML_PAGE)

        # Case 1: data-tooltip + title + .has-tip style + hover toggle
        page.hover("#hastip")
        c1_open = page.evaluate("""() => {
            const plain = document.getElementById('plain');
            const ht = document.getElementById('hastip');
            const tip = document.getElementById('tip-hastip');
            return {
                plain_weight: getComputedStyle(plain).fontWeight,
                hastip_weight: getComputedStyle(ht).fontWeight,
                hastip_cursor: getComputedStyle(ht).cursor,
                hastip_border_bottom_style: getComputedStyle(ht).borderBottomStyle,
                tip_visible_on_hover: getComputedStyle(tip).display === 'block',
                tip_text: tip.textContent,
                tip_bg: getComputedStyle(tip).backgroundColor,
            };
        }""")
        page.mouse.move(10, 10)
        hidden_after = page.evaluate("() => getComputedStyle(document.getElementById('tip-hastip')).display")
        c1 = {**c1_open, "tip_display_after_leave": hidden_after}
        exp1 = {
            "plain_weight": "400",
            "hastip_weight": "700",
            "hastip_cursor": "help",
            "hastip_border_bottom_style": "dotted",
            "tip_visible_on_hover": True,
            "tip_text": "Hooray!",
            "tip_bg": "rgb(51, 51, 51)",
            "tip_display_after_leave": "none",
        }
        cases.append(dict(name="tooltip_data_attr_title_and_has_tip_style", passed=(c1 == exp1), expected=exp1, actual=c1))

        # Case 2: 4 directions geometry
        dirs = {}
        for key, sel, tip_id in [
            ("top", "#t-top", "tip-t-top"),
            ("bottom", "#t-bot", "tip-t-bot"),
            ("left", "#t-left", "tip-t-left"),
            ("right", "#t-right", "tip-t-right"),
        ]:
            page.hover(sel)
            dirs[key] = page.evaluate(f"""() => {{
                const tr = document.querySelector('{sel}').getBoundingClientRect();
                const pr = document.getElementById('{tip_id}').getBoundingClientRect();
                if ('{key}' === 'top') return pr.bottom <= tr.top;
                if ('{key}' === 'bottom') return pr.top >= tr.bottom;
                if ('{key}' === 'left') return pr.right <= tr.left;
                return pr.left >= tr.right;
            }}""")
            page.mouse.move(10, 10)
        exp2 = {"top": True, "bottom": True, "left": True, "right": True}
        cases.append(dict(name="tooltip_four_directions_positioning", passed=(dirs == exp2), expected=exp2, actual=dirs))

        # Case 3: radius and round corner styles
        radii = {}
        for key, sel, tip_id in [("default", "#r-def", "tip-r-def"), ("radius", "#r-rad", "tip-r-rad"), ("round", "#r-rnd", "tip-r-rnd")]:
            page.hover(sel)
            radii[key] = page.evaluate(f"() => getComputedStyle(document.getElementById('{tip_id}')).borderRadius")
            page.mouse.move(10, 10)
        exp3 = {"default": "0px", "radius": "3px", "round": "1000px"}
        cases.append(dict(name="tooltip_radius_and_round_variants", passed=(radii == exp3), expected=exp3, actual=radii))

        # Case 4: small screen 100% width
        page.set_viewport_size({"width": 375, "height": 600})
        page.evaluate("() => document.querySelector('.stage').style.padding = '80px 20px'")
        page.hover("#hastip")
        c4 = page.evaluate("""() => {
            const pr = document.getElementById('tip-hastip').getBoundingClientRect();
            return { tip_width_at_375: Math.round(pr.width), tip_left_at_375: Math.round(pr.left) };
        }""")
        exp4 = {"tip_width_at_375": 375, "tip_left_at_375": 0}
        cases.append(dict(name="tooltip_small_screen_full_width", passed=(c4 == exp4), expected=exp4, actual=c4))

        browser.close()

    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/foundation-tooltips-lab/explore-tooltips.py

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

下载课程关联工程包:Foundation

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

下载课程关联工程包:Foundation

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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