Web 无障碍实战:ARIA 角色与 WCAG 2.2 合规指南

前端工程(更新于 2026年6月17日)

WCAG 2.2 四大原则

WCAG 2.2 围绕 POUR 四大原则组织合规要求:

原则 英文 核心要求 示例
可感知 Perceivable 信息可被所有用户感知 图片 alt、字幕、对比度
可操作 Operable 界面可通过多种方式操作 键盘导航、足够时间、无闪烁
可理解 Understandable 内容与操作可被理解 一致导航、错误提示、输入帮助
健壮 Robust 可被各类辅助技术解析 有效 HTML、ARIA 语义

ARIA 角色体系

文档结构角色

<header role="banner">
  <nav role="navigation" aria-label="主导航">
    <ul role="menubar">
      <li role="menuitem"><a href="/home">首页</a></li>
      <li role="menuitem" aria-haspopup="true">
        产品
        <ul role="menu">
          <li role="menuitem"><a href="/saas">SaaS</a></li>
          <li role="menuitem"><a href="/api">API</a></li>
        </ul>
      </li>
    </ul>
  </nav>
</header>
<main role="main">
  <article role="article">
    <h2>文章标题</h2>
    <p>正文内容</p>
  </article>
</main>
<footer role="contentinfo">版权信息</footer>

窗口小组角色(Widget Roles)

角色 用途 必需属性 关键交互
button 可点击触发 Enter/Space 激活
checkbox 选中/未选 aria-checked Space 切换
radio 单选项 aria-checked 方向键切换
slider 范围值 aria-valuenow, aria-valuemin, aria-valuemax 方向键增减
tablist / tab 标签页 aria-selected 方向键切换
dialog 模态/非模态 aria-modal Esc 关闭
combobox 可选输入 aria-expanded 上下选择/输入筛选
tree / treeitem 树形结构 aria-expanded 方向键展开折叠

ARIA 属性与状态

核心属性速查

<!-- 标签与描述 -->
<button aria-label="关闭对话框">✕</button>
<input aria-labelledby="name-label" aria-describedby="name-hint">
<span id="name-label">用户名</span>
<span id="name-hint">6-20个字符</span>

<!-- 状态 -->
<div aria-expanded="true" aria-selected="false" aria-checked="mixed">
<div aria-hidden="true" aria-disabled="true" aria-busy="true">

<!-- 关系 -->
<div aria-owns="child-id" aria-controls="panel-id" aria-flowto="next-section">

<!-- 实时区域 -->
<div role="alert" aria-live="assertive">错误信息</div>
<div aria-live="polite" aria-atomic="true" aria-relevant="additions text">状态更新</div>

第一规则:不要滥用 ARIA

如果原生 HTML 元素已具备所需语义和交互,就不要用 ARIA 重新实现。

<!-- ❌ 反模式 -->
<div role="button" tabindex="0" onclick="submit()">提交</div>

<!-- ✅ 正确做法 -->
<button type="submit">提交</button>

实战:无障碍模态框

<div class="modal-overlay" id="modalOverlay" hidden>
  <div
    role="dialog"
    aria-modal="true"
    aria-labelledby="modalTitle"
    aria-describedby="modalDesc"
    class="modal"
  >
    <h2 id="modalTitle">确认删除</h2>
    <p id="modalDesc">此操作不可撤销,确定要删除该记录吗?</p>
    <div class="modal-actions">
      <button class="btn-cancel">取消</button>
      <button class="btn-confirm">确认删除</button>
    </div>
  </div>
</div>
class AccessibleModal {
  constructor(dialogEl) {
    this.dialog = dialogEl;
    this.previousFocus = null;
  }

  open() {
    this.previousFocus = document.activeElement;
    this.dialog.hidden = false;
    const firstFocusable = this.dialog.querySelector(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
    );
    firstFocusable?.focus();
    document.addEventListener('keydown', this.handleKeydown);
  }

  close() {
    this.dialog.hidden = true;
    this.previousFocus?.focus();
    document.removeEventListener('keydown', this.handleKeydown);
  }

  handleKeydown = (e) => {
    if (e.key === 'Escape') this.close();
    if (e.key === 'Tab') this.trapFocus(e);
  };

  trapFocus(e) {
    const focusable = [...this.dialog.querySelectorAll(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
    )];
    const first = focusable[0];
    const last = focusable[focusable.length - 1];
    if (e.shiftKey && document.activeElement === first) {
      e.preventDefault();
      last.focus();
    } else if (!e.shiftKey && document.activeElement === last) {
      e.preventDefault();
      first.focus();
    }
  }
}

实战:无障碍标签页

<div class="tabs">
  <div role="tablist" aria-label="账户设置">
    <button
      role="tab"
      id="tab-profile"
      aria-selected="true"
      aria-controls="panel-profile"
      tabindex="0"
    >个人资料</button>
    <button
      role="tab"
      id="tab-security"
      aria-selected="false"
      aria-controls="panel-security"
      tabindex="-1"
    >安全设置</button>
    <button
      role="tab"
      id="tab-notify"
      aria-selected="false"
      aria-controls="panel-notify"
      tabindex="-1"
    >通知偏好</button>
  </div>

  <div role="tabpanel" id="panel-profile" aria-labelledby="tab-profile">
    <p>个人资料设置内容</p>
  </div>
  <div role="tabpanel" id="panel-security" aria-labelledby="tab-security" hidden>
    <p>安全设置内容</p>
  </div>
  <div role="tabpanel" id="panel-notify" aria-labelledby="tab-notify" hidden>
    <p>通知偏好内容</p>
  </div>
</div>
document.querySelector('[role="tablist"]').addEventListener('keydown', (e) => {
  const tabs = [...e.currentTarget.querySelectorAll('[role="tab"]')];
  const idx = tabs.indexOf(document.activeElement);
  let nextIdx;

  if (e.key === 'ArrowRight') nextIdx = (idx + 1) % tabs.length;
  else if (e.key === 'ArrowLeft') nextIdx = (idx - 1 + tabs.length) % tabs.length;
  else if (e.key === 'Home') nextIdx = 0;
  else if (e.key === 'End') nextIdx = tabs.length - 1;
  else return;

  e.preventDefault();
  tabs.forEach((t) => { t.setAttribute('aria-selected', 'false'); t.tabIndex = -1; });
  tabs[nextIdx].setAttribute('aria-selected', 'true');
  tabs[nextIdx].tabIndex = 0;
  tabs[nextIdx].focus();
});

实战:无障碍表单

<form aria-label="用户注册">
  <div class="field">
    <label for="email">邮箱地址 <span aria-hidden="true">*</span></label>
    <input
      id="email"
      type="email"
      required
      aria-required="true"
      autocomplete="email"
      aria-invalid="false"
      aria-describedby="email-error"
    >
    <span id="email-error" role="alert" aria-live="assertive"></span>
  </div>

  <div class="field">
    <label for="password">密码</label>
    <input
      id="password"
      type="password"
      minlength="8"
      aria-describedby="pwd-rules pwd-strength"
    >
    <span id="pwd-rules">至少8个字符,包含大小写字母和数字</span>
    <span id="pwd-strength" aria-live="polite"></span>
  </div>

  <fieldset>
    <legend>通知方式</legend>
    <label><input type="checkbox" name="notify" value="email"> 邮件</label>
    <label><input type="checkbox" name="notify" value="sms"> 短信</label>
  </fieldset>

  <button type="submit">注册</button>
</form>

自动化检测工具对比

工具 类型 覆盖 WCAG 集成方式 特点
axe-core 运行时库 A/AA CI + 浏览器 最全面,零误报
Lighthouse 审计工具 A CLI / DevTools 综合性能+无障碍
WAVE 浏览器扩展 A/AA 手动 可视化标注
NVDA 屏幕阅读器 手动 真实用户体验
Playwright a11y E2E 测试 A CI 与测试流程集成
import { test } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';

test('无障碍检查', async ({ page }) => {
  await page.goto('/register');
  const results = await new AxeBuilder({ page })
    .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])
    .analyze();
  expect(results.violations).toEqual([]);
});

WCAG 2.2 新增要点

新准则 级别 说明
2.4.11 Focus Appearance AAA 焦点指示器面积 ≥ 2px,对比度 ≥ 3:1
2.4.12 Focus Not Obscured AAA 焦点元素不被其他内容遮挡
3.2.6 Consistent Help A 帮助机制位置在页面间保持一致
3.3.7 Redundant Entry A 同一流程中不要求重复输入已提供的信息
3.3.8 Accessible Authentication AA 认证不依赖认知功能测试

最佳实践总结

  1. 原生元素优先:用 <button><input> 等原生元素替代 ARIA 重造
  2. 焦点管理:模态/路由切换后主动聚焦到合理位置
  3. 实时区域审慎aria-live="assertive" 仅用于关键通知,避免频繁打断
  4. 自动化 + 手动:axe-core 覆盖约 30-40% 问题,屏幕阅读器手动测试不可省略
  5. 持续集成:将无障碍检测纳入 CI 流水线,防止回归

本站提供浏览器本地工具,免注册即可试用 →

#无障碍#ARIA#WCAG#屏幕阅读器#可访问性