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

Foundation 开关

核对 Foundation 5 滑动开关的 checkbox + label 绑定机制、四档尺寸(.large/默认/.small/.tiny)、.radius/.round 圆角变体以及基于同 name 单选按钮的互斥开关组。

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

学完这一章,你能够

创建基本切换开关

Foundation 开关以直观的滑动拨块形式呈现 `On` / `Off` 二态切换,适用于桌面点击与触屏轻触。创建基本开关只需一个 `<div class="switch">` 容器,内部依次放置带唯一 `id` 的 `<input type="checkbox">` 以及 `for` 属性与之匹配的 `<label>`(纯 CSS 驱动,无需额外 JS)。本站离线 Chromium 实测确认:默认关闭时开关轨道为浅灰 `rgb(204, 204, 204)`、白色拨块 `::after` 位于 `left: 4px`;点击 `<label>` 后复选框变为 `checked: true`,轨道切换为主蓝色 `rgb(0, 140, 186)` 且拨块右移至 `left: 36px`;再次点击后准确复位。

开关尺寸与圆角样式

在 `.switch` 容器上叠加 `.large`、`.small` 或 `.tiny` 可按需缩放开关尺寸。离线实测四档尺寸严格单调递减:`.large` 为 `80×40px`、默认尺寸为 `64×32px`、`.small` 为 `56×28px`、`.tiny` 为 `48×24px`。

叠加 `.radius` 或 `.round` 可改变开关外框与内部拨块的圆角形态。离线实测:默认开关轨道与拨块圆角均为 `0px`;`.radius` 为轨道 `4px`、拨块 `3px` 的微圆角矩形;`.round` 则两者均为 `1000px`,呈现胶囊轨道与圆形拨块。

单选互斥开关组

若多个开关之间只能同时开启一项,可将内部 `<input>` 的类型改为 `type="radio"`,并确保同组所有单选开关共享相同的 `name` 属性(例如 `name="myGroup"`),还可借 `checked` 指定初始默认开启项。离线实测两个共享 `name="myGroup"` 的开关初始状态为 `[False, True]`;点击第一个开关标签后立即互斥切换为 `[True, False]`,重复点击已开启项则维持 `[True, False]`。

离线验证 Foundation 5 开关状态切换、四档尺寸、圆角变体与单选互斥组

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

FOUNDATION_CSS = """
*, *::before, *::after { box-sizing: border-box; }
html, body { margin: 0; padding: 16px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 16px; }
.switch { position: relative; margin-bottom: 16px; padding: 0; border: none; }
.switch input { position: absolute; opacity: 0; width: 0; height: 0; }
.switch label {
  display: block; position: relative; cursor: pointer;
  width: 64px; height: 32px; background: #cccccc; border-radius: 0px;
}
.switch label::after {
  content: ""; display: block; position: absolute;
  top: 4px; left: 4px; width: 24px; height: 24px;
  background: #ffffff; border-radius: 0px;
}
.switch input:checked + label { background: #008cba; }
.switch input:checked + label::after { left: 36px; }

.switch.large label { width: 80px; height: 40px; }
.switch.large label::after { width: 32px; height: 32px; top: 4px; left: 4px; }
.switch.large input:checked + label::after { left: 44px; }

.switch.small label { width: 56px; height: 28px; }
.switch.small label::after { width: 20px; height: 20px; top: 4px; left: 4px; }
.switch.small input:checked + label::after { left: 32px; }

.switch.tiny label { width: 48px; height: 24px; }
.switch.tiny label::after { width: 16px; height: 16px; top: 4px; left: 4px; }
.switch.tiny input:checked + label::after { left: 28px; }

.switch.radius label { border-radius: 4px; }
.switch.radius label::after { border-radius: 3px; }
.switch.round label { border-radius: 1000px; }
.switch.round label::after { border-radius: 1000px; }
"""

HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{FOUNDATION_CSS}</style></head>
<body>
  <div class="switch"><input id="mySwitch" type="checkbox"><label id="lbl-basic" for="mySwitch"></label></div>

  <div class="switch large"><input id="swLarge" type="checkbox"><label id="lbl-large" for="swLarge"></label></div>
  <div class="switch"><input id="swDef" type="checkbox"><label id="lbl-def" for="swDef"></label></div>
  <div class="switch small"><input id="swSmall" type="checkbox"><label id="lbl-small" for="swSmall"></label></div>
  <div class="switch tiny"><input id="swTiny" type="checkbox"><label id="lbl-tiny" for="swTiny"></label></div>

  <div class="switch radius"><input id="swRad" type="checkbox"><label id="lbl-rad" for="swRad"></label></div>
  <div class="switch round"><input id="swRnd" type="checkbox"><label id="lbl-rnd" for="swRnd"></label></div>

  <div class="switch"><input id="mySwitch1" type="radio" name="myGroup"><label id="lbl-r1" for="mySwitch1"></label></div>
  <div class="switch"><input id="mySwitch2" type="radio" name="myGroup" checked><label id="lbl-r2" for="mySwitch2"></label></div>
</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": 600, "height": 600})
        page.set_content(HTML_PAGE)

        # Case 1: basic checkbox switch toggle via label for/id
        def read_basic():
            return page.evaluate("""() => {
                const inp = document.getElementById('mySwitch');
                const lbl = document.getElementById('lbl-basic');
                return {
                    checked: inp.checked,
                    track_bg: getComputedStyle(lbl).backgroundColor,
                    knob_left: getComputedStyle(lbl, '::after').left,
                };
            }""")

        off_state = read_basic()
        page.click("#lbl-basic")
        on_state = read_basic()
        page.click("#lbl-basic")
        off_again = read_basic()
        c1 = {"off": off_state, "on": on_state, "off_again": off_again}
        exp1 = {
            "off": {"checked": False, "track_bg": "rgb(204, 204, 204)", "knob_left": "4px"},
            "on": {"checked": True, "track_bg": "rgb(0, 140, 186)", "knob_left": "36px"},
            "off_again": {"checked": False, "track_bg": "rgb(204, 204, 204)", "knob_left": "4px"},
        }
        cases.append(dict(name="checkbox_switch_toggle_and_label_for", passed=(c1 == exp1), expected=exp1, actual=c1))

        # Case 2: four switch sizes
        c2 = page.evaluate("""() => {
            const ids = ['lbl-large', 'lbl-def', 'lbl-small', 'lbl-tiny'];
            const dims = {};
            for (const id of ids) {
                const r = document.getElementById(id).getBoundingClientRect();
                dims[id.replace('lbl-', '')] = [Math.round(r.width), Math.round(r.height)];
            }
            dims.monotonic = dims.large[0] > dims.def[0] && dims.def[0] > dims.small[0] && dims.small[0] > dims.tiny[0];
            return dims;
        }""")
        exp2 = {
            "large": [80, 40],
            "def": [64, 32],
            "small": [56, 28],
            "tiny": [48, 24],
            "monotonic": True,
        }
        cases.append(dict(name="switch_four_sizes", passed=(c2 == exp2), expected=exp2, actual=c2))

        # Case 3: default vs radius vs round corners
        c3 = page.evaluate("""() => ({
            default_track: getComputedStyle(document.getElementById('lbl-def')).borderRadius,
            default_knob: getComputedStyle(document.getElementById('lbl-def'), '::after').borderRadius,
            radius_track: getComputedStyle(document.getElementById('lbl-rad')).borderRadius,
            radius_knob: getComputedStyle(document.getElementById('lbl-rad'), '::after').borderRadius,
            round_track: getComputedStyle(document.getElementById('lbl-rnd')).borderRadius,
            round_knob: getComputedStyle(document.getElementById('lbl-rnd'), '::after').borderRadius,
        })""")
        exp3 = {
            "default_track": "0px",
            "default_knob": "0px",
            "radius_track": "4px",
            "radius_knob": "3px",
            "round_track": "1000px",
            "round_knob": "1000px",
        }
        cases.append(dict(name="switch_radius_and_round_corners", passed=(c3 == exp3), expected=exp3, actual=c3))

        # Case 4: radio switch group mutual exclusion
        init_r = page.evaluate("() => [document.getElementById('mySwitch1').checked, document.getElementById('mySwitch2').checked]")
        page.click("#lbl-r1")
        after_r1 = page.evaluate("() => [document.getElementById('mySwitch1').checked, document.getElementById('mySwitch2').checked]")
        page.click("#lbl-r1")
        after_r1_again = page.evaluate("() => [document.getElementById('mySwitch1').checked, document.getElementById('mySwitch2').checked]")
        c4 = {
            "shared_name": page.evaluate("() => document.getElementById('mySwitch1').name === document.getElementById('mySwitch2').name && document.getElementById('mySwitch1').name === 'myGroup'"),
            "initial": init_r,
            "after_click_1": after_r1,
            "after_click_1_again": after_r1_again,
        }
        exp4 = {
            "shared_name": True,
            "initial": [False, True],
            "after_click_1": [True, False],
            "after_click_1_again": [True, False],
        }
        cases.append(dict(name="radio_switch_group_mutual_exclusion", passed=(c4 == exp4), expected=exp4, actual=c4))

        browser.close()

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


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 在离线 Chromium 中核对 checkbox 开关背景与拨块位移切换、large/默认/small/tiny 单调尺寸、0px/4px/1000px 圆角以及同 name radio 开关组互斥行为。
离线验证 Foundation 5 开关状态切换、四档尺寸、圆角变体与单选互斥组

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

当前源码 SHA256:c2bec03b67632649065ae82f58d87e43f07159245b678c986760788aa79a8053

下载本站示例源码

本地运行

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

下载Foundation 开关实验

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

ZIP SHA256:9304790a75d78615aa711fe86ea0dd8745ba1bb8409f56c753923fe995cf9774

常见错误与边界

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

练习与解答

Foundation 开关中 <label> 的 for 属性与 <input> 的 id 不一致会导致什么问题?如何实现多个开关互斥单选?

展开参考解答

由于真实表单控件被视觉隐藏,点击开关依赖 <label for="..."> 触发对应 <input>;若 for 与 id 不匹配,点击开关外观将无法改变选中状态。实现互斥单选需把 type 改为 radio 并为同组开关设置相同的 name 属性。

规范与官方依据