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

Foundation 表单

核对 Foundation 5 表单控件全局 100% 宽度与内阴影样式、<label> 焦点联动与 .right 右对齐、<fieldset>/<legend> 分组框及 .error 错误态动态校验。

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

学完这一章,你能够

表单控件全局默认样式

Foundation 5 无需额外类前缀即可自动美化标准 HTML 表单控件:所有 `<input>`、`<textarea>` 与 `<select>` 默认撑满容器 `100%` 宽度,统一配备下外边距、内边距、细微内阴影以及聚焦背景与边框过渡。本站离线 Playwright Chromium 在 `600px` 宽容器内实测确认三类控件宽度均为 `600px`,`margin-bottom: 16px`、`padding: 8px`,具备 `inset` 内阴影,且 `<input>` 获得焦点后背景切换为浅灰 `rgb(250, 250, 250)`。

表单标签 <label> 联动与右对齐

表单字段应配合 `<label>` 使用,并通过 `for` 属性绑定控件的唯一 `id`(亦可将控件嵌套在 `<label>` 内),这样点击标签文本即可把输入焦点直接切换到对应控件,提升可访问性与移动端点击命中率。离线实测依次点击 `#lbl-name`、`#lbl-adr`、`#lbl-num` 后,`document.activeElement.id` 准确依次切换为 `name`、`adr`、`num`。

若布局需要将标签文字靠右排布(常见于水平表单左列),可为 `<label>` 添加 `.right` 类。实测 `<label class="right">` 计算样式为 `float: right` 与 `text-align: right`。

字段分组容器 <fieldset> 与 <legend>

使用语义化 `<fieldset>` 与 `<legend>` 可把相关表单项归入带浅灰细边框的分组卡片。离线实测 `<fieldset>` 边框色为 `rgb(221, 221, 221)`、内边距 `20px`、上下外边距 `18px`,`<legend>` 以 `font-weight: 700` 粗体与纯白背景 `rgb(255, 255, 255)` 清晰截断顶边线。

表单错误状态 .error 与脚本校验提示

当输入校验不通过时,可为 `<label>`、`<input>`、`<textarea>` 以及紧随其后的 `<small>` 提示块添加 `.error` 类以醒目警示。实测 `.error` 状态下标签文字与控件边框均转为红色 `rgb(240, 65, 36)`,`<small class="error">` 呈红底白字块级条幅(`display: block`)。同时须注意 Foundation CSS 本身只负责呈现错误样式,实际校验逻辑需借助 JavaScript(或 Abide 插件)在用户输入与提交时动态增删 `.error`:实测填入 5 字符有效姓名后 `.error` 移除、错误条幅转为 `display: none`,改回 1 字符短输入后错误态立即恢复。

表单错误状态交互提示

要点实现说明
错误状态更新方式CSS `.error` 仅提供视觉警示样式,必须使用 JavaScript 在输入或提交校验时动态切换 `.error` 类与 `<small class="error">` 提示

离线验证 Foundation 5 表单控件全局样式、标签聚焦、Fieldset 分组与错误态切换

python · 阅读源码
"""Offline Playwright Chromium lab for Foundation Ch 23 (forms)."""
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; }
.container { width: 600px; margin: 20px auto; }
form { margin: 0 0 16px; }
label { font-size: 14px; color: #4d4d4d; cursor: pointer; display: block; font-weight: 400; line-height: 1.5; margin-bottom: 0; }
label.right { float: right; text-align: right; }
input[type="text"], textarea, select {
  display: block;
  width: 100%;
  margin: 0 0 16px 0;
  padding: 8px;
  border: 1px solid #cccccc;
  background-color: #ffffff;
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
  color: rgba(0, 0, 0, 0.75);
  font-size: 14px;
}
input[type="text"]:focus, textarea:focus, select:focus {
  background: #fafafa;
  border-color: #999999;
  outline: none;
}
fieldset { border: 1px solid #dddddd; padding: 20px; margin: 18px 0; }
fieldset legend { font-weight: 700; background: #ffffff; padding: 0 3px; margin: 0 0 0 -3px; }
label.error { color: #f04124; }
label.error input, label.error textarea, input.error, textarea.error {
  border-color: #f04124;
  background-color: rgba(240, 65, 36, 0.1);
  margin-bottom: 0;
}
small.error {
  display: block;
  padding: 6px 9px 9px;
  margin-top: -1px;
  margin-bottom: 16px;
  font-size: 12px;
  font-weight: 400;
  font-style: italic;
  background: #f04124;
  color: #ffffff;
}
small.error.hidden { display: none; }
"""

HTML_PAGE = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"><style>{FOUNDATION_CSS}</style></head>
<body>
  <div class="container">
    <form id="f-basic">
      <input id="basic-input" type="text" placeholder="Name">
      <textarea id="basic-textarea" rows="4" placeholder="Address"></textarea>
      <select id="basic-select">
        <option>1</option><option>2</option><option>3</option><option>4</option>
      </select>
    </form>

    <form id="f-labels">
      <label id="lbl-name" for="name">Input
        <input type="text" placeholder="Name" id="name">
      </label>
      <label id="lbl-adr" for="adr">Label
        <textarea rows="4" placeholder="Address" id="adr"></textarea>
      </label>
      <label id="lbl-num" for="num">Select
        <select id="num"><option>1</option><option>2</option></select>
      </label>
      <label id="lbl-right" class="right">Right Aligned Label</label>
    </form>

    <form id="f-fieldset" style="clear:both;">
      <fieldset id="fs">
        <legend id="fs-legend">Fieldset Legend</legend>
        <label>Name <input type="text" placeholder="First Name.."></label>
        <label>Email <input type="text" placeholder="Enter email.."></label>
      </fieldset>
    </form>

    <form id="f-error">
      <label id="err-lbl" class="error">Error
        <input id="err-input" type="text" placeholder="Name..">
      </label>
      <small id="err-msg" class="error">Wrong input</small>
      <textarea id="err-ta" class="error" rows="4" placeholder="Address"></textarea>
      <small id="err-ta-msg" class="error">Wrong input</small>
    </form>
  </div>
  <script>
    const errInput = document.getElementById('err-input');
    const errLbl = document.getElementById('err-lbl');
    const errMsg = document.getElementById('err-msg');
    errInput.addEventListener('input', () => {{
      const invalid = errInput.value.trim().length < 3;
      errLbl.classList.toggle('error', invalid);
      errMsg.classList.toggle('hidden', !invalid);
    }});
  </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": 800, "height": 900})
        page.set_content(HTML_PAGE)

        # Case 1: global form controls full width & styling
        page.focus("#basic-input")
        c1 = page.evaluate("""() => {
            const inp = document.getElementById('basic-input');
            const ta = document.getElementById('basic-textarea');
            const sel = document.getElementById('basic-select');
            const is = getComputedStyle(inp);
            const ts = getComputedStyle(ta);
            const ss = getComputedStyle(sel);
            return {
                input_width: Math.round(inp.getBoundingClientRect().width),
                textarea_width: Math.round(ta.getBoundingClientRect().width),
                select_width: Math.round(sel.getBoundingClientRect().width),
                margin_bottom: is.marginBottom,
                padding_top: is.paddingTop,
                has_inset_shadow: is.boxShadow.includes('inset'),
                focused_bg: is.backgroundColor,
                textarea_margin_bottom: ts.marginBottom,
                select_margin_bottom: ss.marginBottom,
            };
        }""")
        exp1 = {
            "input_width": 600,
            "textarea_width": 600,
            "select_width": 600,
            "margin_bottom": "16px",
            "padding_top": "8px",
            "has_inset_shadow": True,
            "focused_bg": "rgb(250, 250, 250)",
            "textarea_margin_bottom": "16px",
            "select_margin_bottom": "16px",
        }
        cases.append(dict(name="global_form_controls_full_width_and_styles", passed=(c1 == exp1), expected=exp1, actual=c1))

        # Case 2: label for/id focus linkage and .right alignment
        page.click("#lbl-name")
        f1 = page.evaluate("() => document.activeElement.id")
        page.click("#lbl-adr")
        f2 = page.evaluate("() => document.activeElement.id")
        page.click("#lbl-num")
        f3 = page.evaluate("() => document.activeElement.id")
        right_style = page.evaluate("""() => {
            const s = getComputedStyle(document.getElementById('lbl-right'));
            return { float: s.float, text_align: s.textAlign };
        }""")
        c2 = {
            "focus_after_label_name": f1,
            "focus_after_label_adr": f2,
            "focus_after_label_num": f3,
            "right_float": right_style["float"],
            "right_text_align": right_style["text_align"],
        }
        exp2 = {
            "focus_after_label_name": "name",
            "focus_after_label_adr": "adr",
            "focus_after_label_num": "num",
            "right_float": "right",
            "right_text_align": "right",
        }
        cases.append(dict(name="label_for_focus_and_right_align", passed=(c2 == exp2), expected=exp2, actual=c2))

        # Case 3: fieldset & legend styling
        c3 = page.evaluate("""() => {
            const fs = getComputedStyle(document.getElementById('fs'));
            const lg = getComputedStyle(document.getElementById('fs-legend'));
            return {
                fieldset_border_color: fs.borderTopColor,
                fieldset_padding: fs.paddingTop,
                fieldset_margin_top: fs.marginTop,
                legend_font_weight: lg.fontWeight,
                legend_bg: lg.backgroundColor,
            };
        }""")
        exp3 = {
            "fieldset_border_color": "rgb(221, 221, 221)",
            "fieldset_padding": "20px",
            "fieldset_margin_top": "18px",
            "legend_font_weight": "700",
            "legend_bg": "rgb(255, 255, 255)",
        }
        cases.append(dict(name="fieldset_and_legend_styling", passed=(c3 == exp3), expected=exp3, actual=c3))

        # Case 4: error state styling & JS dynamic validation toggle
        before_err = page.evaluate("""() => {
            const lbl = getComputedStyle(document.getElementById('err-lbl'));
            const inp = getComputedStyle(document.getElementById('err-input'));
            const msg = getComputedStyle(document.getElementById('err-msg'));
            return {
                label_color: lbl.color,
                input_border_color: inp.borderTopColor,
                small_bg: msg.backgroundColor,
                small_color: msg.color,
                small_display: msg.display,
            };
        }""")
        page.fill("#err-input", "Alice")
        valid_state = page.evaluate("""() => ({
            has_error_class: document.getElementById('err-lbl').classList.contains('error'),
            small_display: getComputedStyle(document.getElementById('err-msg')).display,
        })""")
        page.fill("#err-input", "A")
        invalid_again = page.evaluate("""() => ({
            has_error_class: document.getElementById('err-lbl').classList.contains('error'),
            small_display: getComputedStyle(document.getElementById('err-msg')).display,
        })""")
        c4 = {"initial_error": before_err, "after_valid_input": valid_state, "after_short_input": invalid_again}
        exp4 = {
            "initial_error": {
                "label_color": "rgb(240, 65, 36)",
                "input_border_color": "rgb(240, 65, 36)",
                "small_bg": "rgb(240, 65, 36)",
                "small_color": "rgb(255, 255, 255)",
                "small_display": "block",
            },
            "after_valid_input": {"has_error_class": False, "small_display": "none"},
            "after_short_input": {"has_error_class": True, "small_display": "block"},
        }
        cases.append(dict(name="error_state_and_js_validation", passed=(c4 == exp4), expected=exp4, actual=c4))

        browser.close()

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


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 在离线 Chromium 中核对 input/textarea/select 100% 宽度与内阴影、label for/id 聚焦及 .right 右对齐、fieldset 边框与 .error 动态校验切换。
离线验证 Foundation 5 表单控件全局样式、标签聚焦、Fieldset 分组与错误态切换

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

当前源码 SHA256:6f5ff1cdb9d3287fa2ed01f10cfb26b59bd662d83f91f4ecffefd35f490ce2c7

下载本站示例源码

本地运行

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

下载Foundation 表单实验

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

ZIP SHA256:dfc4718eb27f8e28f3cb89b595f96c2e6783c5bafb4f94fd33a37b8593dca6c5

常见错误与边界

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

练习与解答

在 Foundation 5 表单中,只给 <label> 和 <small> 加上 .error 类能否自动完成用户输入校验?为什么?

展开参考解答

不能。.error 类仅控制红色文字、红色边框与错误提示条幅的 CSS 外观,输入规则判断及 .error 类的增删必须由 JavaScript(或校验插件)根据输入内容实时或提交时更新。

规范与官方依据