Skip to content

无障碍 a11y ​

a11y = "accessibility"(中间 11 个字母简称)。让残障用户也能用你的网站——盲人 / 弱视 / 色盲 / 听障 / 行动不便 / 认知障碍。

为什么重要(不只是道德):
  - 1 in 4 美国人有某种残障(WHO)
  - 法律要求(美国 ADA / 欧盟 EAA / 国内信息无障碍条例)
  - SEO 加分(语义化 HTML 利于爬虫)
  - 老年用户 / 临时障碍(手骨折 / 强光下) 也受益
  - 苹果 / 谷歌 / 政府采购 强制要求 WCAG AA

不做 a11y = 法律风险 + 流失用户 + 拿不到 B 端订单。


一、WCAG:行业标准 ​

WCAG(Web Content Accessibility Guidelines)由 W3C 制定:

WCAG 2.1(2018)/ 2.2(2023)
四大原则(POUR):
  Perceivable    可感知 — 信息要能被感官获取
  Operable       可操作 — 键盘 / 触控都能用
  Understandable 可理解 — 内容清晰
  Robust         健壮 — 各种辅助技术兼容

三个级别:
  A    最低,基本可用
  AA   主流目标,大部分企业要求
  AAA  最严,内容站点 / 政府推荐

目标:WCAG 2.1 AA。AAA 实在难达成,A 太低。


二、a11y 受影响的用户 ​

视障(盲)
  → 屏幕阅读器(VoiceOver / NVDA / JAWS / TalkBack)读出来
  → 你的页面要"能被读出来 + 顺序合理"

弱视
  → 放大字体 / 高对比度
  → 字号要响应缩放 + 配色对比够

色盲(8% 男性)
  → 不要只用颜色传递信息(红色错误 → 加图标 / 文字)

听障
  → 视频要字幕,音频要文字稿

行动障碍 / 老年
  → 键盘代替鼠标 / 大点击区域 / 简单交互

癫痫
  → 不要每秒闪烁 > 3 次

认知障碍
  → 简单语言,避免歧义,清晰的错误提示

三、HTML 语义化(基础) ​

最大的 a11y 提升来自用对 HTML 标签。屏幕阅读器靠语义识别页面结构。

1. 用对元素 ​

html
<!-- ❌ 全部 div,屏幕阅读器抓瞎 -->
<div class="header">
  <div class="nav">
    <div class="link" onclick="...">Home</div>
  </div>
</div>
<div class="main">
  <div class="title">Title</div>
  <div class="btn" onclick="submit()">Submit</div>
</div>

<!-- ✅ 语义化 -->
<header>
  <nav>
    <a href="/">Home</a>
  </nav>
</header>
<main>
  <h1>Title</h1>
  <button type="submit" onClick={submit}>Submit</button>
</main>

<button> 自带:

  • 键盘 Enter / Space 触发
  • 焦点环
  • 屏幕阅读器读"按钮"
  • 表单内默认 type=submit

<div onclick> 这些全部要自己加(且很难做对)。

2. 标题层级 ​

html
<h1>页面主标题(每页一个)</h1>
<h2>章节</h2>
<h3>子章节</h3>
<h4>更小</h4>

不要跳级(<h1> 直接到 <h3>)。屏幕阅读器有"按标题导航"功能,层级乱用户找不到内容。

3. landmarks(地标) ​

html
<header>
<nav>
<main>      ← 主要内容,每页一个
<aside>      ← 侧栏 / 相关内容
<footer>
<section aria-labelledby="title">
  <h2 id="title">章节</h2>
</section>
<article>    ← 独立内容(博客文章)

屏幕阅读器有"按 landmark 跳转"快捷键,让用户跳过 nav 直接到主要内容。

4. 列表 ​

html
<ul>
  <li>...</li>
</ul>

<ol>
  <li>...</li>
</ol>

屏幕阅读器读"3 项的列表",用户知道"还有 2 项"。手写 <div> 列表丢了这信息。

5. 表单 ​

html
<!-- ❌ 没 label,屏幕阅读器读不出输入框是干啥的 -->
<input type="email" placeholder="Email">

<!-- ✅ -->
<label for="email">Email</label>
<input id="email" type="email">

<!-- 或包裹 -->
<label>
  Email
  <input type="email">
</label>

<label> 必加。placeholder 不能替代 label(用户输入后看不到提示了)。


四、ARIA(必要时再用) ​

1. ARIA 是什么 ​

ARIA = "Accessible Rich Internet Applications" 属性,给屏幕阅读器额外信息。

html
<div role="button" tabindex="0" aria-label="Close" onclick="close()">×</div>

ARIA 第一原则:能用原生 HTML 就别用 ARIA。<button> 自带所有,<div role="button"> 要写 5 个属性才能模拟一半。

2. role:语义补充 ​

html
<div role="button">          人工告诉它是按钮(不如用 <button>)
<div role="navigation">       人工告诉它是 nav(不如用 <nav>)
<div role="alert">            重要警报,自动朗读
<div role="status">           状态变化(轻量提示)
<div role="dialog">           弹窗
<div role="tablist">          tab 列表
<div role="menu">             菜单

3. aria-label / aria-labelledby:无形 label ​

html
<!-- 图标按钮没文字,屏幕阅读器读不出 -->
<button aria-label="Close">×</button>

<!-- 引用其他元素的文字 -->
<h2 id="title">Settings</h2>
<section aria-labelledby="title">...</section>

<!-- 关联说明 -->
<input aria-describedby="hint">
<small id="hint">必须 8 位以上</small>

4. aria-expanded / aria-hidden / aria-current ​

html
<!-- 折叠面板状态 -->
<button aria-expanded="false" aria-controls="panel">More</button>
<div id="panel" hidden>...</div>

<!-- 隐藏装饰元素(不影响屏幕阅读器) -->
<svg aria-hidden="true">...</svg>

<!-- 当前页 / 当前步骤 -->
<a href="/about" aria-current="page">About</a>

5. 实时区域 ​

html
<!-- 通知 / 提示 -->
<div role="status" aria-live="polite">
  保存成功
</div>

<!-- 重要警告(打断用户) -->
<div role="alert" aria-live="assertive">
  错误:输入有误
</div>

polite = 等用户停顿了再读,assertive = 立即读。Toast / 错误提示必加。

6. ARIA 用错警告 ​

html
<!-- ❌ 有 <button> 不用,自己模拟 -->
<div role="button" tabindex="0" onkeydown="if (e.key === 'Enter') ..." onclick="...">

<!-- ❌ 重复语义 -->
<button role="button">     button 已经是 button

<!-- ❌ aria-hidden 但能 focus -->
<button aria-hidden="true">  按钮被隐藏却能 tab 到,体验崩坏

ARIA 强,但滥用比不用还糟。


五、键盘导航 ​

1. 所有交互必须键盘可达 ​

Tab            前进
Shift+Tab      后退
Enter          激活按钮 / 链接
Space          激活按钮 / toggle
Arrow keys     菜单 / 列表导航
Esc            关闭弹窗

2. 焦点环必须可见 ​

css
/* ❌ 千万别这么写 */
*:focus { outline: none; }

/* ✅ 自定义焦点环但保留 */
:focus-visible {
  outline: 2px solid #3b82f6;
  outline-offset: 2px;
}

:focus-visible 只在键盘聚焦时显示焦点(鼠标点不显示),两全其美。

3. tabindex ​

html
<div tabindex="0">     可以聚焦,正常顺序
<div tabindex="-1">    不在 tab 顺序里(但 JS 可以 .focus())
<div tabindex="5">     ❌ 别用正数,会打乱顺序

tabindex 只用 0 和 -1。

4. 焦点管理(SPA / 弹窗 / 抽屉) ​

ts
// 弹窗打开时把焦点移到弹窗
useEffect(() => {
  if (open) dialogRef.current?.focus();
}, [open]);

// 关闭时返回到触发按钮
const triggerRef = useRef();
const close = () => {
  setOpen(false);
  triggerRef.current?.focus();
};

焦点陷阱(focus trap):弹窗内 tab 不出去:

ts
// 用 focus-trap 库,或 Radix 内置
import { FocusTrap } from 'focus-trap-react';

<FocusTrap>
  <Dialog>...</Dialog>
</FocusTrap>
html
<a href="#main" class="skip-link">Skip to main content</a>
...
<main id="main" tabindex="-1">...</main>
css
.skip-link {
  position: absolute;
  left: -9999px;
}
.skip-link:focus {
  left: 0;
  z-index: 10;
}

键盘用户按 Tab 第一下就看到 "Skip to main content",按 Enter 直接跳到主内容。官网首页必加。


六、视觉:对比度 + 字号 ​

1. 颜色对比度 ​

WCAG AA:

  • 正常文字 ≥ 4.5:1
  • 大文字(18pt+ / 14pt 加粗) ≥ 3:1
  • UI 组件 / 图标 ≥ 3:1

工具:

浅灰 #999 on white:2.84:1 ❌(不够)
中灰 #767676 on white:4.54:1 ✅

2. 不要只用颜色传信息 ​

❌ 只有红字表示错误,色盲用户看不到
✅ 红字 + ❌ 图标 + "Error: " 文字
❌ 只有红绿区分上涨下跌(中国股市的红涨绿跌也会困惑)
✅ 红绿 + ↑↓ 箭头 + 数字加正负号

3. 字号 ​

最小 16px(默认浏览器字号),手机 14px
不用固定 px,用 rem(用户能放大)

font-size: 1rem;       16px
font-size: 1.125rem;    18px

4. 缩放 200% 不破 ​

用户可能放大到 200%(浏览器 / 操作系统),布局不能错乱。

测试:Chrome 缩放 → 200%,跑一遍主流程。

5. 暗色模式 ​

css
@media (prefers-color-scheme: dark) {
  body { background: #1a1a1a; color: #fafafa; }
}

或用 CSS 变量切主题。对比度仍要 4.5:1(暗色模式不能纯黑 #000 白 #fff,刺眼 + 散光严重)。


七、动效:别造成不适 ​

1. 尊重用户偏好 ​

css
@media (prefers-reduced-motion: reduce) {
  * {
    animation-duration: 0.01s !important;
    transition-duration: 0.01s !important;
  }
}

用户在系统设置里勾"减少动画"(为前庭疾病 / 晕动症患者),你的页面要尊重。

ts
// JS 检测
const prefersReduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
if (!prefersReduced) playAnimation();

2. 闪烁警告 ​

每秒闪烁 > 3 次可能引发癫痫。不要做闪烁的元素。

3. 自动播放视频 ​

带声音的自动播放 = a11y 大忌。默认静音或完全不要自动播放。


八、表单 a11y ​

html
<!-- 必填 -->
<label for="email">
  Email <span aria-hidden="true">*</span>
  <span class="sr-only">required</span>
</label>
<input id="email" type="email" required aria-required="true">

<!-- 错误 -->
<label for="pw">Password</label>
<input id="pw" type="password" aria-invalid="true" aria-describedby="pw-error">
<div id="pw-error" role="alert">至少 8 位</div>

<!-- 帮助文字 -->
<label for="user">Username</label>
<input id="user" aria-describedby="user-help">
<small id="user-help">3-20 字符,字母数字</small>

<!-- 分组 -->
<fieldset>
  <legend>Gender</legend>
  <label><input type="radio" name="g" value="m"> Male</label>
  <label><input type="radio" name="g" value="f"> Female</label>
</fieldset>

.sr-only = 只给屏幕阅读器看,视觉隐藏:

css
.sr-only {
  position: absolute;
  width: 1px; height: 1px;
  margin: -1px; padding: 0;
  overflow: hidden;
  clip: rect(0,0,0,0);
  white-space: nowrap;
  border: 0;
}

或 Tailwind 内置 sr-only class。


九、图片 / 图标 / 媒体 ​

图片 ​

html
<!-- 有信息的图(必加 alt) -->
<img src="logo.png" alt="Acme Corp 公司 Logo">

<!-- 装饰图(空 alt,屏幕阅读器跳过) -->
<img src="decoration.svg" alt="">

<!-- SVG 图标 -->
<svg aria-hidden="true">...</svg>          装饰
<svg role="img" aria-label="Search">       有意义的
  ...
</svg>

<!-- 复杂图(用 figure) -->
<figure>
  <img src="chart.png" alt="2023 年销量图">
  <figcaption>详细描述...</figcaption>
</figure>

alt 写法:

  • 目的比"内容"重要:不写 "三个人在桌前",写 "团队会议"
  • 不要 "image of" / "picture of",屏幕阅读器自己会说
  • 装饰图用空 alt(alt=""),不写 alt 屏幕阅读器读 src URL,灾难

视频 ​

html
<video controls>
  <source src="movie.mp4" type="video/mp4">
  <track kind="captions" src="captions.vtt" srclang="en" label="English">
</video>

<track> 提供字幕。商业视频应该提供:

  • 字幕(captions)
  • 文字稿(transcript)
  • 音频描述(audio description,描述视觉内容)

十、SPA 路由 a11y ​

SPA 切路由不是真的页面跳转,屏幕阅读器不知道页面变了。

ts
// 路由变化时通知
useEffect(() => {
  document.title = 'Dashboard - My App';   // 标题反映页面
  // 把焦点放到 main
  mainRef.current?.focus();
}, [pathname]);

或用专门的 react-aria-live 库播报"已导航到 X 页"。

Next.js / Nuxt 内置部分支持。


十一、组件库的 a11y ​

做 a11y 不要从零写组件:用 Headless UI 库
他们已经做好键盘 / ARIA / 焦点

Radix UI       React,无样式,a11y 满分
Headless UI    Tailwind 团队
React Aria      Adobe,行业标杆
Reach UI       (维护中,部分迁移到 Radix)
Ark UI          多框架(React / Vue / Solid)
shadcn/ui      基于 Radix,直接拷贝代码

自己写 Modal / Dropdown / Combobox 几乎不可能 a11y 完美(键盘 / 焦点 / ARIA 太多细节)。用现成的。


十二、测试 ​

1. 自动化(能查 30%) ​

bash
pnpm add -D axe-core @axe-core/react jest-axe
tsx
import { axe } from 'jest-axe';

test('no a11y violations', async () => {
  const { container } = render(<App />);
  expect(await axe(container)).toHaveNoViolations();
});

或 Playwright:

ts
import AxeBuilder from '@axe-core/playwright';

test('a11y', async ({ page }) => {
  await page.goto('/');
  const results = await new AxeBuilder({ page }).analyze();
  expect(results.violations).toEqual([]);
});

2. 浏览器工具 ​

Chrome DevTools → Lighthouse → Accessibility
axe DevTools 扩展(免费)
WAVE 扩展
Polypane(付费,专业 a11y 浏览器)

3. 手动(70% 要靠这个) ​

  • 关掉鼠标,用 Tab 跑完所有交互
  • 打开屏幕阅读器:
    • macOS:VoiceOver(Cmd+F5)
    • Windows:NVDA(免费)
    • iOS:VoiceOver
    • Android:TalkBack
  • 缩放到 200% 看是否破版
  • 色盲模拟(Chrome DevTools → Rendering → Emulate vision deficiencies)

十三、常见 Trap ​

Trap 1:用 div 模拟按钮 ​

html
<!-- ❌ -->
<div class="btn" onclick="submit()">Submit</div>

<!-- ✅ -->
<button onclick="submit()">Submit</button>

Trap 2:placeholder 当 label ​

html
<!-- ❌ -->
<input placeholder="Email">

<!-- ✅ -->
<label for="email">Email</label>
<input id="email" placeholder="alice@example.com">

Trap 3:outline: none ​

css
/* ❌ */
*:focus { outline: none; }

/* ✅ */
:focus-visible { outline: 2px solid blue; }

Trap 4:hover-only 交互 ​

按钮 hover 才出现菜单 = 触屏 / 键盘用户用不了。改成 click 或 focus 触发。

Trap 5:小点击区 ​

按钮 16x16px 太小,Apple 推荐 44x44px 最小。手机用户老人都受益。

Trap 6:依赖颜色 ​

❌ 红字 = 错,绿字 = 对
✅ 红字 + ❌ + "错误:..."  / 绿字 + ✓ + "已验证"

Trap 7:tabindex 正数 ​

tabindex="5" 强制顺序 = 灾难,屏幕阅读器迷路。只用 0 / -1。

Trap 8:aria-hidden 套了可交互元素 ​

html
<!-- ❌ -->
<div aria-hidden="true">
  <button>Click</button>     按钮被屏幕阅读器忽略,但能 focus,体验崩
</div>

十四、a11y 实战 checklist ​

结构 ​

  • [ ] 用语义化 HTML(<button> <nav> <main> 等),不是全 <div>
  • [ ] 标题 h1-h6 不跳级
  • [ ] 每页一个 h1
  • [ ] 有 <main> 标签
  • [ ] Skip link 跳过导航
  • [ ] lang 属性:<html lang="zh-CN">

键盘 ​

  • [ ] 所有交互能 Tab 到
  • [ ] Tab 顺序合理
  • [ ] 焦点可见(:focus-visible)
  • [ ] 弹窗有焦点陷阱
  • [ ] Esc 关闭弹窗
  • [ ] 列表 / 菜单支持方向键

视觉 ​

  • [ ] 字号 ≥ 16px,字段 ≥ 14px
  • [ ] 对比度 ≥ 4.5:1
  • [ ] 不只用颜色传信息
  • [ ] 焦点环明显
  • [ ] 缩放 200% 不破
  • [ ] 暗色模式对比度也合格

文本与媒体 ​

  • [ ] 图片 alt(装饰图 alt="")
  • [ ] 视频字幕
  • [ ] 链接文字描述目的(避免 "click here")
  • [ ] 表单 label 关联

ARIA ​

  • [ ] 自定义组件用 ARIA(用现成 Radix 最好)
  • [ ] 实时区域(role="status" / "alert")用于通知
  • [ ] aria-current 标当前
  • [ ] aria-expanded 标展开状态
  • [ ] aria-hidden 标装饰

测试 ​

  • [ ] axe / Lighthouse 0 严重错误
  • [ ] 关闭鼠标完整跑一遍
  • [ ] 屏幕阅读器跑关键路径
  • [ ] 缩放 200%

十五、心智模型 ​

a11y 三层:
  1. 语义化 HTML(80% 受益)
     用对标签 = 自动可达
  2. 键盘 + 焦点(15%)
     Tab 顺序 / 焦点环 / 焦点陷阱
  3. ARIA(5%,自定义复杂组件)
     必要时给屏幕阅读器额外信息

不写 a11y 的代价:
  法律风险 + 招聘流失 + B 端拿不到单 + 良心不安

写 a11y 的好处:
  代码更语义化(设计更清晰)
  SEO 更好(语义化爬虫友好)
  老人 / 临时残障用户也受益
  你也是潜在受益者(40 岁老花了)

十六、推荐学习路径 ​

  1. 这一篇 + checklist 过一遍现有项目
  2. 装 axe DevTools 跑一遍页面
  3. 关掉鼠标 5 分钟跑你自己的产品
  4. 跟 W3C WAI tutorial 走一遍:https://www.w3.org/WAI/tutorials/
  5. 做关键页面用 Radix / React Aria 重写

十七、参考资源 ​

下一篇 41 讲国际化 i18n。