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

Foundation 提示框

核对 Foundation 5 悬停提示框(Tooltips)的 data-tooltip/title 属性、.has-tip 强调样式、四方向定位类、小屏 100% 宽度行为及 .radius/.round 圆角。

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

学完这一章,你能够

创建基本提示框与 .has-tip 强调样式

Foundation 提示框用于在鼠标悬停目标元素时浮现简短补充说明。任意元素只要添加 `data-tooltip` 属性并用 `title` 指定提示文本,再经 `$(document).foundation();` 初始化 JavaScript 插件即可生效(初始化时会接管原生 `title` 属性以避免浏览器重复弹出默认气泡)。

为触发元素额外添加 `.has-tip` 类可将其排版为加粗、带虚线下划线且鼠标呈问号指针的可提示词条,提示用户此处存在交互说明。本站离线 Chromium 实测确认:普通 `<span data-tooltip>` 字重为 `400`,而 `.has-tip` 为 `font-weight: 700`、`border-bottom-style: dotted`、`cursor: help`;悬停后弹出深灰背景 `rgb(51, 51, 51)`、文本为 `Hooray!` 的 `.tooltip` 浮层,移开指针后恢复 `display: none`。

提示框四个显示方向与小屏适配

提示框默认显示在目标元素正下方(`.tip-bottom`),也可通过 `.tip-top`、`.tip-left` 或 `.tip-right` 分别指定上方、左侧或右侧弹出。在小尺寸屏幕(`≤40em`)下,提示框会自动扩展至 `100%` 视口宽度以避免边缘裁切。本站离线实测在 `900×500` 视口下四个方向几何边界全部精确满足(`top` 底部不高于触发器顶、`bottom` 顶部不低于触发器底、`left` 右缘不超触发器左、`right` 左缘不小于触发器右);将视口缩窄至 `375px` 后,悬停提示框宽度立即撑满 `375px` 且左缘对齐 `0px`。

圆角提示框 .radius 与 .round

在带有 `data-tooltip` 的触发元素上叠加 `.radius` 或 `.round`,生成的提示框浮层会继承对应的圆角样式。离线实测三种变体的计算 `border-radius` 依次为默认 `0px`、`.radius` 为 `3px`、`.round` 为 `1000px`。

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

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 在离线 Chromium 中核对 .has-tip 加粗虚线与悬停显隐、tip-top/bottom/left/right 相对坐标、default/radius/round 圆角以及 375px 视口 100% 宽度。
离线验证 Foundation 5 提示框悬停显隐、.has-tip 样式、四向定位与小屏通栏宽度

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

当前源码 SHA256:fd004ef59b5275eb52767f58663969e1aa52a4087e0b34494a96c56dbd1ae696

下载本站示例源码

本地运行

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

下载Foundation 提示框实验

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

ZIP SHA256:a0d6fcbd2e7788d8e70509a64ff14672037a37753f2ffe39183626f62cead834

常见错误与边界

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

练习与解答

在 Foundation 5 中,创建提示框必须具备哪两个 HTML 属性?添加 .has-tip 类会产生什么视觉提示?

展开参考解答

必须在目标元素上添加 data-tooltip 属性和 title 属性(并初始化 Foundation JS);.has-tip 会将触发文本加粗、添加点状下划线并将光标设为 help,明确提示读者可悬停查看说明。

规范与官方依据