← 中文资源

简体中文版本

用 fieldset 与 legend 对单选按钮分组

使用 fieldset 和 legend 命名单选组,为每个选项配标签,并让整组只占一个 Tab 停靠点。

阅读英文原文

题目

结算页提供三档配送速度。这些选项必须作为名为“配送速度”的一组被播报,配送说明要随组一起提供;键盘行为应保持原生单选组语义:整组只有一个 Tab 停靠点,方向键在组内切换选项。

  • 输入:三档配送选项(含价格)与一条配送时间说明。
  • 输出:带 legend 的 fieldset、带标签且共享 name 的单选框,以及通过 aria-describedby 关联的说明。
  • 公开样例:屏幕阅读器进入组时播报组名与说明;Tab 只停在已选项,方向键在组内移动。

解题思路

fieldset 与首个 legend 子元素共同构成组名,这是原生语义,不需要额外加 role="radiogroup"。三个 input[type=radio] 必须共享同一个 name,浏览器才会把它们视为互斥组,并只保留一个 Tab 停靠点。每个选项用 id 与 for 和 label 配对,点击文字也能选中。说明文字不要塞进 legend,而应放在独立段落中,用 fieldset 上的 aria-describedby 关联,让组名保持简短。最后给默认项加 checked,确保提交时总有值。

参考实现要点

  1. fieldset 上设置 aria-describedby="shipping-hint",内部第一行是 legend。
  2. 说明段落使用 id="shipping-hint",解释预计送达时间的起算点。
  3. 三个单选框统一 name="shipping",value 分别为 standard、express、overnight。
  4. 每个 label 的 for 与对应输入的 id 完全一致,标签文字包含价格与时效。
  5. 默认项加 checked,提交按钮使用 type="submit"。

常见错误

  • 三个单选框使用不同 name,方向键失效,而且每个选项都成为独立 Tab 停靠点。
  • 用 div 或 h3 充当组标题,组没有可访问名称。
  • 把整段说明写进 legend,组名过长,播报时难以抓住重点。
  • 只写 id 不写 for,点击标签文字无法选中选项。

验证方式

用 Tab 进入表单,焦点应只落在已选项上;按方向键确认选择在组内移动且不离开组,再按 Tab 应到提交按钮。无障碍树中确认组名为“配送速度”、描述为说明文字。逐个点击标签文字,确认对应单选框被选中;提交后检查请求中包含所选 value。

代码示例

<form>
  <fieldset aria-describedby="shipping-hint">
    <legend>Shipping speed</legend>
    <p id="shipping-hint">Delivery estimates start when the order leaves the warehouse.</p>

    <div>
      <input type="radio" id="ship-standard" name="shipping" value="standard" checked>
      <label for="ship-standard">Standard - $4, 5 to 7 business days</label>
    </div>

    <div>
      <input type="radio" id="ship-express" name="shipping" value="express">
      <label for="ship-express">Express - $12, 2 business days</label>
    </div>

    <div>
      <input type="radio" id="ship-overnight" name="shipping" value="overnight">
      <label for="ship-overnight">Overnight - $28, next business day</label>
    </div>
  </fieldset>

  <button type="submit">Continue to payment</button>
</form>