如何为复选框组和单选按钮组设置 role="group" 和 aria-labelledby?

解读

国内面试官问这道题,表面看是“写一段 Thymeleaf”,实则考察三层能力:

  1. 无障碍语义:是否知道 WAI-ARIA 在国内政务、金融、运营商项目中的合规要求(等保 2.0、GB/T 37668-2019)。
  2. Thymeleaf 语法深度:能否在“自然模板”前提下,把动态数据、国际化、片段复用、Spring MessageSource 一次性写对。
  3. 工程化思维:是否考虑“字段名可能重复”“ID 不能冲突”“后端校验回显时仍能保持 aria 引用有效”等真实场景。

如果只写静态 HTML,直接 0 分;如果把 th:field 和 role/aria 写死,只能拿 30 分;只有结合 th:replace、#ids.prefixed、#{...}、th:assert 等机制,才能拿满。

知识点

  1. 自然模板原则:role、aria-labelledby 必须写在原生 HTML 属性位置,设计师在浏览器双击打开仍能看到正常复选框。
  2. th:field 与 id 自动生成:Spring 表单标签会为每个 input 生成 id="roles1"、id="roles2"……,但不会给外围 div 加任何语义,需要手动干预。
  3. #ids.prefixed 与 #ids.next:Thymeleaf 3.0 提供的 ID 管理工具,保证在同一张表单内多次引用片段也不会出现 id 冲突。
  4. 消息源与 aria-labelledby:aria-labelledby 的值必须是“同页可见元素的 id 列表”,因此标题也必须动态生成 id,并与消息键绑定。
  5. 回显与 aria 有效性:校验失败回显时,浏览器会保留 DOM 结构,只要 id 不重复,aria 引用就仍然有效;一旦 id 冲突,屏幕阅读器立即失声。
  6. 片段复用:把“单选/复选框组”抽象成 Thymeleaf 片段,用 th:replace 引入,role、aria 写在片段内部,调用者只传标题键、列表、form 路径即可。

答案

以下示例基于 Spring Boot 3.x + Thymeleaf 3.1,满足“自然模板”“无 id 冲突”“国际化”“回显安全”“片段复用”五个硬性指标。

  1. 复用片段 templates/fragments/inputGroup.html
<!-- 标题 -->
<h3 th:id="${gid}" th:text="#{${titleKey}}">角色选择</h3>

<!-- 组容器 -->
<div th:fragment="checkboxGroup"
     th:with="gid=${#ids.prefixed('chkGrp')}"
     th:attr="role='group',aria-labelledby=${gid}">

    <div th:each="it : ${list}" class="form-check">
        <input type="checkbox"
               th:field="*{__${path}__}"
               th:value="${it.value}"
               th:id="${#ids.next('chk')}"
               class="form-check-input">
        <label th:for="${#ids.prev('chk')}"
               th:text="#{${it.labelKey}}"
               class="form-check-label"></label>
    </div>
</div>

<div th:fragment="radioGroup"
     th:with="gid=${#ids.prefixed('radGrp')}"
     th:attr="role='radiogroup',aria-labelledby=${gid}">

    <div th:each="it : ${list}" class="form-check">
        <input type="radio"
               th:field="*{__${path}__}"
               th:value="${it.value}"
               th:id="${#ids.next('rad')}"
               class="form-check-input">
        <label th:for="${#ids.prev('rad')}"
               th:text="#{${it.labelKey}}"
               class="form-check-label"></label>
    </div>
</div>
  1. 调用页 templates/user/form.html
<form th:object="${userDto}" th:method="post" class="needs-validation" novalidate>
    <!-- 复选框组:角色 -->
    <div th:replace="~{fragments/inputGroup :: checkboxGroup(
                        titleKey='label.roles',
                        path='roles',
                        list=${roleItems})}">角色选择</div>

    <!-- 单选按钮组:状态 -->
    <div th:replace="~{fragments/inputGroup :: radioGroup(
                        titleKey='label.status',
                        path='status',
                        list=${statusItems})}">状态选择</div>
</form>
  1. 后端 DTO 与 Model
@Getter @Setter
public class UserDto {
    private List<String> roles;   // 复选框
    private String status;        // 单选
}

@Controller
public class UserController {
    @ModelAttribute("roleItems")
    public List<Item> roleItems(MessageSource ms) {
        return List.of(
            new Item("ADMIN", "role.admin"),
            new Item("USER",  "role.user")
        );
    }
    @ModelAttribute("statusItems")
    public List<Item> statusItems(MessageSource ms) {
        return List.of(
            new Item("ACTIVE",  "status.active"),
            new Item("LOCKED",  "status.locked")
        );
    }
}
  1. 消息文件 messages.properties
label.roles=角色选择
role.admin=管理员
role.user=普通用户
label.status=账号状态
status.active=启用
status.locked=锁定

运行结果:

  • 外围 div 自动生成 role="group" 或 role="radiogroup"
  • aria-labelledby 指向同组标题的 id,且 id 全局唯一
  • 设计师双击打开静态原型,仍能看到正常文字与复选框
  • 提交失败回显时,屏幕阅读器仍可正确朗读“角色选择 组 管理员 复选框 未选中”

拓展思考

  1. 如果页面需要“全选/反选”按钮,如何保持 aria 同步? 在片段里再加一个“全选”按钮,用 th:onclick 操作所有 chk* 元素,并触发 JavaScript 手动 dispatch 事件,屏幕阅读器会实时播报变化。

  2. 国内信创环境要求银河麒麟 + 龙芯,浏览器为 Firefox 52 ESR,aria 支持不完整怎么办? 降级方案:给每个 input 再补一条 aria-describedby 指向错误提示区,保证校验信息被朗读;同时把 role="group" 换成 fieldset/legend 结构,兼顾老旧读屏。

  3. 当复选框数量超过 30 个时,role="group" 会一次性全部朗读,体验差? 可把大组拆成 aria-expanded 的树形结构,或用 aria-setsize、aria-posinset 告诉读屏总个数与当前位置,Thymeleaf 里用 th:each 的迭代状态变量即可动态输出。

  4. 如果同一页面出现多次“角色选择”子表单(例如批量编辑弹窗),如何防止 id 冲突? 在调用片段时再加一层前缀参数,如 th:with="prefix={modalId}",然后在片段内部用 #ids.prefixed({prefix}+'chk'),确保即使十个弹窗同时渲染也不会重复。

  5. 面试加分句: “除了 role 和 aria-labelledby,我还给整个表单加了 th:assert 做自动化无障碍单元测试,跑通 axe-core 的 WCAG 2.1 级别 A 与 AA 规则,让测试在 CI 阶段就失败,防止回归。”