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

Foundation 选项卡

核对 Foundation 5 水平与垂直选项卡 .tabs/.tab-title/.vertical 布局、.tabs-content/.content.active 切换机制以及 CSS fadeEffect 淡入动画实测结果。

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

学完这一章,你能够

水平选项卡与垂直选项卡

选项卡(Tabs)适合在同一视区空间内分组呈现并切换多块关联内容。Foundation 5 使用 `<ul class="tabs" data-tab>` 定义选项卡导航栏,每个选项写在 `<li class="tab-title">` 中,当前激活项通过 `.active` 类标出。本站离线 Chromium 实测:4 个水平 `.tab-title` 项位于同一行且从左向右紧凑排列,激活项链接背景为纯白 `rgb(255, 255, 255)`,未激活项背景为浅灰 `rgb(239, 239, 239)`。

若页面更适合左侧栏切换风格,只需在 `<ul>` 上追加 `.vertical` 类(`<ul class="tabs vertical" data-tab>`),并通常配合右侧 `.tabs-content.vertical` 内容区使用。本站在 `800px` 容器内实测 `.tabs.vertical` 宽 `160px`(`20%`),3 个选项左边界对齐且沿垂直方向严格向下堆叠。

内容区联动切换机制

要让点击选项卡真正切换下方内容,需在 `<div class="tabs-content">` 内为每个面板创建带 `.content` 类与唯一 `id` 的 `<div>`,并让导航项 `<a href="#menu1">` 指向对应 `id="menu1"`,最后初始化 Foundation JS(`$(document).foundation()`)。切换时脚本会自动将 `.active` 类移到当前选中的 `.tab-title` 与对应的 `.content` 面板上。本站离线实测:初始仅 `#home` 显示(`display: block`),点击 `Menu 1` 后激活项与可见面板同步切换为 `t-m1` / `['menu1']`,点击 `Menu 3` 后切换为 `t-m3` / `['menu3']`。

自定义 CSS 淡入切换动画

默认切换为瞬时显隐;若希望新激活的面板平滑显现,可为 `.tabs-content > .content.active` 绑定自定义 `@keyframes fadeEffect`(从 `opacity: 0` 过渡到 `opacity: 1`,时长 `1s`,同时兼容 `-webkit-` 前缀)。本站离线 Chromium 实测激活态 `.content.active` 的计算样式 `animationName` 为 `fadeEffect`、`animationDuration` 为 `1s`。

离线验证 Foundation 5 水平/垂直选项卡、面板切换与 CSS fadeEffect 动画

python · 阅读源码
"""Offline Playwright Chromium lab for Foundation 5 Ch 16 (tabs)."""
import json
from playwright.sync_api import sync_playwright

FOUNDATION_TABS_CSS = """
*, *::before, *::after { box-sizing: border-box; }
html { font-size: 16px; }
body { margin: 0; padding: 20px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; color: #222; background: #fff; }
.tabs {
  list-style: none;
  margin: 0;
  padding: 0;
}
.tabs::before, .tabs::after { content: " "; display: table; }
.tabs::after { clear: both; }
.tabs .tab-title {
  position: relative;
  margin-bottom: 0;
  list-style: none;
  float: left;
}
.tabs .tab-title > a {
  display: block;
  background-color: #EFEFEF;
  color: #222222;
  padding: 1rem 2rem;
  font-size: 1rem;
  text-decoration: none;
}
.tabs .tab-title.active > a {
  background-color: #FFFFFF;
  color: #222222;
}
.tabs.vertical {
  width: 20%;
  max-width: 20%;
  float: left;
  margin: 0 0 1.25rem;
}
.tabs.vertical .tab-title {
  float: none;
  display: block;
}
.tabs-content {
  margin-bottom: 1.5rem;
  width: 100%;
}
.tabs-content > .content {
  display: none;
  float: left;
  padding: 0.9375rem 0;
  width: 100%;
}
.tabs-content > .content.active {
  display: block;
  float: none;
  -webkit-animation: fadeEffect 1s;
  animation: fadeEffect 1s;
}
.tabs-content.vertical {
  width: 80%;
  max-width: 80%;
  float: left;
  padding-left: 1rem;
}
@-webkit-keyframes fadeEffect {
  from { opacity: 0; }
  to { opacity: 1; }
}
@keyframes fadeEffect {
  from { opacity: 0; }
  to { opacity: 1; }
}
"""

HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{FOUNDATION_TABS_CSS}</style></head>
<body>
  <ul id="tabs-main" class="tabs" data-tab>
    <li id="t-home" class="tab-title active"><a href="#home">Home</a></li>
    <li id="t-m1" class="tab-title"><a href="#menu1">Menu 1</a></li>
    <li id="t-m2" class="tab-title"><a href="#menu2">Menu 2</a></li>
    <li id="t-m3" class="tab-title"><a href="#menu3">Menu 3</a></li>
  </ul>
  <div id="content-main" class="tabs-content">
    <div class="content active" id="home"><h3>HOME</h3><p>Home content.</p></div>
    <div class="content" id="menu1"><h3>Menu 1</h3><p>First tab content.</p></div>
    <div class="content" id="menu2"><h3>Menu 2</h3><p>Second tab content.</p></div>
    <div class="content" id="menu3"><h3>Menu 3</h3><p>Last tab content.</p></div>
  </div>

  <div style="width: 800px; overflow: hidden; margin-top: 24px;">
    <ul id="tabs-vert" class="tabs vertical" data-tab>
      <li class="tab-title active"><a href="#v1">V-Tab 1</a></li>
      <li class="tab-title"><a href="#v2">V-Tab 2</a></li>
      <li class="tab-title"><a href="#v3">V-Tab 3</a></li>
    </ul>
    <div class="tabs-content vertical">
      <div class="content active" id="v1"><p>Vertical panel 1</p></div>
      <div class="content" id="v2"><p>Vertical panel 2</p></div>
      <div class="content" id="v3"><p>Vertical panel 3</p></div>
    </div>
  </div>

  <script>
    (function () {{
      document.querySelectorAll('ul.tabs[data-tab]').forEach((ul) => {{
        ul.querySelectorAll('li.tab-title > a').forEach((a) => {{
          a.addEventListener('click', (e) => {{
            e.preventDefault();
            const targetId = (a.getAttribute('href') || '').replace(/^#/, '');
            const target = document.getElementById(targetId);
            if (!target) return;
            ul.querySelectorAll('li.tab-title').forEach((li) => li.classList.remove('active'));
            a.parentElement.classList.add('active');
            const container = target.parentElement;
            container.querySelectorAll(':scope > .content').forEach((c) => c.classList.remove('active'));
            target.classList.add('active');
          }});
        }});
      }});
    }})();
  </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": 1000, "height": 800})
        page.set_content(HTML_PAGE)

        # Case 1: horizontal_tabs_and_active_style
        act_1 = page.evaluate("""() => {
            const items = Array.from(document.querySelectorAll('#tabs-main > li.tab-title'));
            const rects = items.map(li => li.getBoundingClientRect());
            const sameRow = rects.every(r => Math.abs(r.top - rects[0].top) <= 1);
            const strictlyRight = rects.every((r, i) => i === 0 || r.left >= rects[i - 1].right - 1);
            const activeBg = getComputedStyle(items[0].querySelector('a')).backgroundColor;
            const inactiveBg = getComputedStyle(items[1].querySelector('a')).backgroundColor;
            return {
                same_row: sameRow,
                strictly_left_to_right: strictlyRight,
                active_bg: activeBg,
                inactive_bg: inactiveBg,
            };
        }""")
        exp_1 = {
            "same_row": True,
            "strictly_left_to_right": True,
            "active_bg": "rgb(255, 255, 255)",
            "inactive_bg": "rgb(239, 239, 239)",
        }
        cases.append({
            "name": "horizontal_tabs_and_active_style",
            "expected": exp_1,
            "actual": act_1,
            "passed": act_1 == exp_1,
        })

        # Case 2: vertical_tabs_layout
        act_2 = page.evaluate("""() => {
            const ul = document.getElementById('tabs-vert');
            const items = Array.from(ul.querySelectorAll('li.tab-title'));
            const rects = items.map(li => li.getBoundingClientRect());
            const sameLeft = rects.every(r => Math.abs(r.left - rects[0].left) <= 1);
            const strictlyDown = rects.every((r, i) => i === 0 || r.top >= rects[i - 1].bottom - 1);
            return {
                vert_width: Math.round(ul.getBoundingClientRect().width),
                same_left: sameLeft,
                strictly_vertical: strictlyDown,
            };
        }""")
        exp_2 = {
            "vert_width": 160,
            "same_left": True,
            "strictly_vertical": True,
        }
        cases.append({
            "name": "vertical_tabs_layout",
            "expected": exp_2,
            "actual": act_2,
            "passed": act_2 == exp_2,
        })

        # Case 3: toggleable_tabs_content_switch
        def tab_state():
            return page.evaluate("""() => ({
                active_tab: document.querySelector('#tabs-main > li.tab-title.active').id,
                visible_panels: Array.from(document.querySelectorAll('#content-main > .content'))
                    .filter(el => getComputedStyle(el).display === 'block')
                    .map(el => el.id),
            })""")

        s0 = tab_state()
        page.locator('#t-m1 a').click()
        s1 = tab_state()
        page.locator('#t-m3 a').click()
        s2 = tab_state()
        act_3 = {"initial": s0, "after_menu1": s1, "after_menu3": s2}
        exp_3 = {
            "initial": {"active_tab": "t-home", "visible_panels": ["home"]},
            "after_menu1": {"active_tab": "t-m1", "visible_panels": ["menu1"]},
            "after_menu3": {"active_tab": "t-m3", "visible_panels": ["menu3"]},
        }
        cases.append({
            "name": "toggleable_tabs_content_switch",
            "expected": exp_3,
            "actual": act_3,
            "passed": act_3 == exp_3,
        })

        # Case 4: tabs_css_fade_animation
        act_4 = page.evaluate("""() => {
            const activePanel = document.querySelector('#content-main > .content.active');
            const s = getComputedStyle(activePanel);
            return {
                animation_name: s.animationName,
                animation_duration: s.animationDuration,
            };
        }""")
        exp_4 = {
            "animation_name": "fadeEffect",
            "animation_duration": "1s",
        }
        cases.append({
            "name": "tabs_css_fade_animation",
            "expected": exp_4,
            "actual": act_4,
            "passed": act_4 == exp_4,
        })

        browser.close()
    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 在离线 Chromium 中核对水平选项卡同行激活色、垂直选项卡 20% 宽纵向堆叠、点击切换 .active 状态及 fadeEffect 1s 动画计算属性。
离线验证 Foundation 5 水平/垂直选项卡、面板切换与 CSS fadeEffect 动画

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

当前源码 SHA256:aaad952091297c13b4ed25afb03c5da9a108e2caf23443d2fff9ac60d0c7507c

下载本站示例源码

本地运行

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

下载Foundation 选项卡实验

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

ZIP SHA256:78b7fcb12fd93bd6d5b4493da6e9caafa629f2c6ae5a74c1d58bcf5acbe6d490

常见错误与边界

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

练习与解答

在 Foundation 5 选项卡中,点击 <a href="#menu2"> 后页面上的哪两个元素会自动获得 .active 类?

展开参考解答

包含该链接的 <li class="tab-title"> 与 .tabs-content 容器中对应的 <div id="menu2" class="content"> 会同步获得 .active 类,其余同级选项卡与面板的 .active 类会被移除。

规范与官方依据