可访问性(a11y)工程化:从检查到组件约束
MrSmy Lv5

“可访问性”在国内项目里经常是”等有合规要求再说”的事。我们做这件事的起点很现实:一个政务项目要过等保 + 无障碍测评,被指出了 47 个问题,其中 31 个是同一类。

这篇讲怎么把它做成工程能力而不是一次性整改。

三次失败的尝试

第一次(2021 年):装个 axe 插件,人工扫

结果:扫出 300 多个告警,没人看得懂”ARIA role 不匹配”是什么意思,一个月后所有人把插件关了。

第二次(2022 年):写进测试用例

1
2
3
4
5
test('页面无 a11y 问题', async ({ page }) => {
await page.goto('/')
const results = await new AxeBuilder({ page }).analyze()
expect(results.violations).toHaveLength(0)
})

结果:积压了 180 个违规,CI 永远红,两周后被人加了 test.skip。

第三次(2024 年):从组件层解决

核心转变:不改页面,改组件库。

因为 80% 的 a11y 问题都来自那几个基础组件——Button、Input、Select、Modal、Table、Tooltip。把组件做对,页面自然就对了。

组件层的六条硬约束

1. 按钮:能按回车、有焦点样式、禁用不靠颜色

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Button({ variant = 'primary', disabled, loading, children, ...rest }) {
return (
<button
type="button" // 默认 type,防止在 form 里意外提交
className={cx('btn', `btn--${variant}`)}
disabled={disabled || loading}
aria-busy={loading || undefined}
{...rest}
>
{loading && <Spinner aria-hidden="true" />}
{children}
</button>
)
}

三个细节:

  • type="button":不写的话 <button> 默认 type="submit",放在表单里会触发提交。我们在一个”取消”按钮上踩过这个坑。
  • aria-busy:告诉屏幕阅读器”正在处理”,而不是让它读”禁用”。
  • Spinner 加 aria-hidden:避免读屏器读出装饰元素。

焦点样式是重灾区。大量项目写 outline: none:

1
2
/* 错误做法:键盘用户完全看不到当前位置 */
*:focus { outline: none }

正确做法:

1
2
3
4
5
6
7
8
9
10
/* 只在键盘导航时显示焦点环 */
:focus-visible {
outline: 2px solid var(--color-brand);
outline-offset: 2px;
}

/* 鼠标点击不显示(可选,但要慎用) */
:focus:not(:focus-visible) {
outline: none;
}

:focus-visible 的浏览器启发式规则:键盘 Tab 触发的焦点会显示,鼠标点击不会。这正是我们想要的。

2. 表单:label 必须真的关联

1
2
3
4
5
6
7
8
9
10
11
12
13
// 错误:视觉上有 label,但读屏器不知道关联
<label>邮箱</label>
<input name="email" />

// 正确:htmlFor + id
<label htmlFor="email">邮箱</label>
<input id="email" name="email" type="email" autoComplete="email" />

// 也可以包裹(但布局受限)
<label>
邮箱
<input name="email" />
</label>

错误提示必须能被读到:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<div className="field">
<label htmlFor="email">邮箱</label>
<input
id="email"
type="email"
aria-invalid={!!error || undefined}
aria-describedby={error ? 'email-error' : undefined}
/>
{error && (
<p id="email-error" role="alert" className="error">
{error}
</p>
)}
</div>

aria-describedby 让读屏器在聚焦时读出错误信息;role="alert" 让错误出现时立即播报(不用用户主动聚焦)。

这里有个细节:role="alert" 的元素必须在 DOM 里先存在(可以是空),错误时填内容才会播报。如果是错误时才创建元素,部分读屏器不会播报。可靠的做法是用 aria-live 容器:

1
<p aria-live="polite" className="error">{error}</p>   // 一直存在,内容变化时播报

3. 模态框:焦点必须被关在里面

这是最复杂的组件。要求:

  • 打开时焦点移入
  • Tab 循环在内部(不跑到背景)
  • 关闭时焦点回到触发元素
  • 背景内容 aria-hidden
  • Esc 关闭

用原生 <dialog> 能省很多事:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function Modal({ open, onClose, title, children }) {
const ref = useRef<HTMLDialogElement>(null)

useEffect(() => {
const el = ref.current
if (!el) return
if (open && !el.open) el.showModal() // showModal 自带焦点陷阱和 Esc
if (!open && el.open) el.close()
}, [open])

return (
<dialog ref={ref} onClose={onClose} aria-labelledby="modal-title">
<h2 id="modal-title">{title}</h2>
{children}
</dialog>
)
}

showModal() 的行为(浏览器原生实现):

能力 原生 <dialog> 手写 div
焦点陷阱 自动 要自己写
Esc 关闭 自动 要自己写
背景 inert 自动(::backdrop) 要手动 aria-hidden + inert
顶层渲染 自动(不受 z-index/overflow 影响) 要 Portal
滚动锁定 需自己加 需自己加

唯一的坑:showModal() 后 dialog 会在 top layer,z-index 不管用,position: fixed 的子元素也只相对 dialog。我们这个坑踩过——一个下拉框溢出到了 dialog 外面被裁剪。

4. 表格:语义标签不能省

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 错误:用 div 拼表格
<div className="row">
<div className="cell">姓名</div>
<div className="cell">年龄</div>
</div>

// 正确
<table>
<caption className="sr-only">员工列表</caption>
<thead>
<tr>
<th scope="col">姓名</th>
<th scope="col">年龄</th>
</tr>
</thead>
<tbody>
<tr>
<td>张三</td>
<td>28</td>
</tr>
</tbody>
</table>

scope="col" 让读屏器在读到单元格时告知”这是哪一列”。可排序的表头加 aria-sort:

1
2
3
<th scope="col" aria-sort={sortKey === 'age' ? (desc ? 'descending' : 'ascending') : 'none'}>
<button onClick={() => toggle('age')}>年龄</button>
</th>

caption 或 aria-label 两者至少有一个——否则读屏器只说”表格,3 行 2 列”,用户不知道是什么表。

5. 图标按钮:必须有可访问名称

1
2
3
4
5
6
7
8
9
10
11
12
13
// 错误:读屏器读"按钮"
<button onClick={close}><CloseIcon /></button>

// 正确 1:aria-label
<button onClick={close} aria-label="关闭">
<CloseIcon aria-hidden="true" />
</button>

// 正确 2:视觉隐藏文本(支持 i18n,推荐)
<button onClick={close}>
<CloseIcon aria-hidden="true" />
<span className="sr-only">关闭</span>
</button>
1
2
3
4
5
6
7
8
9
10
11
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}

**为什么推荐 .sr-only**:aria-label 是硬编码字符串,走不了 i18n(有的读屏器会按语言读,但很多项目忘了给 aria-label 做翻译)。.sr-only 文本是普通内容,跟着翻译走。

6. 图片:alt 分三种情况

1
2
3
4
5
6
7
8
// 有信息量的图:描述内容
<img src="/chart.png" alt="2025 年 Q1-Q4 营收:Q1 120 万,Q4 280 万" />

// 纯装饰:空 alt(不是省略 alt)
<img src="/divider.svg" alt="" role="presentation" />

// 图标按钮里的图标:aria-hidden
<button aria-label="搜索"><SearchIcon aria-hidden="true" /></button>

最容易错的是”省略 alt”。没有 alt 属性时,读屏器会读出文件名(”chart dash 2025 dot png”),比空 alt 更糟。

自动化检查:放在什么位置

第一层:ESLint(写的时候就拦)

1
npm i -D eslint-plugin-jsx-a11y
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// eslint.config.js
import jsxA11y from 'eslint-plugin-jsx-a11y'

export default [
{
plugins: { 'jsx-a11y': jsxA11y },
rules: {
...jsxA11y.flatConfigs.recommended.rules,
// 我们自己加严的两条
'jsx-a11y/no-autofocus': 'error',
'jsx-a11y/media-has-caption': 'error',
},
},
]

jsx-a11y 能抓:img 缺 alt、a 缺 href、onClick 挂在非交互元素上、label 关联缺失、role 拼错等。这些是”编译期”能发现的,成本最低。

第二层:组件层单测(保证每个组件单个正确)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { Button } from './Button'

test('可以用键盘触发', async () => {
const onClick = vi.fn()
render(<Button onClick={onClick}>保存</Button>)

const btn = screen.getByRole('button', { name: '保存' })
btn.focus()
await userEvent.keyboard('{Enter}')
expect(onClick).toHaveBeenCalled()
})

test('loading 时告知无障碍状态', () => {
render(<Button loading>保存</Button>)
expect(screen.getByRole('button')).toHaveAttribute('aria-busy', 'true')
expect(screen.getByRole('button')).toBeDisabled()
})

用 getByRole 而不是 getByTestId 本身就是 a11y 检查——拿不到 role 说明语义不对。

第三层:E2E + axe(保证页面组合后仍正确)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import AxeBuilder from '@axe-core/playwright'

const PAGES = ['/', '/orders', '/settings', '/orders/123']

for (const path of PAGES) {
test(`${path} 无严重 a11y 问题`, async ({ page }) => {
await page.goto(path)
const { violations } = await new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa'])
.analyze()

const serious = violations.filter((v) => v.impact === 'critical' || v.impact === 'serious')
expect(serious, JSON.stringify(serious.map((v) => ({
id: v.id,
nodes: v.nodes.map((n) => n.target),
})), null, 2)).toHaveLength(0)
})
}

关键在 impact 过滤。axe 的告警分 critical / serious / moderate / minor,全都要 0 是不现实的(很多是第三方组件的问题)。我们只卡前两档,moderate 用 report 方式输出到 PR 评论。

第四层:键盘走查(自动化的盲区)

自动化只能发现约 30-40% 的 a11y 问题。剩下的必须人工:

1
2
3
4
5
6
7
## 键盘走查清单(每个新页面 5 分钟)

- [ ] 只按 Tab,能不能到达所有交互元素?顺序是否符合视觉顺序?
- [ ] 焦点环是否始终可见?有没有被 `overflow: hidden` 裁掉?
- [ ] Esc 能不能关掉所有浮层?
- [ ] 下拉/日期选择器能否用方向键操作?
- [ ] 移动端能否正常缩放(没有 `user-scalable=no`)?

把这份清单放在 PR 模板里,比写在文档里有效得多。

自动化抓不到的四类问题

这是我们必须承认的边界:

问题类型 为什么抓不到 例子
语义错误 axe 只知道”有没有 label”,不知道”label 说得对不对” alt="图片"、aria-label="按钮"
焦点顺序 需要真实交互 DOM 顺序和视觉顺序相反
阅读顺序 需要理解内容 用 CSS 把”确认”放在”取消”左边
认知负担 无法量化 表单字段太多、错误提示太隐晦

alt="图片" 这类”形式合规”是最危险的——它让自动化变绿,但用户得到的体验和没有 alt 一样。

对比度:最容易被低估的一项

WCAG AA 要求:正文 4.5:1,大字号(18.5px 粗体 / 24px)3:1。

我们的设计系统里有几个”看起来还行”的颜色,实测不达标:

Token 颜色 在白底上的对比度 结果
--color-text-secondary #8a8f98 3.4:1 不达标
--color-text-tertiary #a8adb7 2.2:1 严重不达标
--color-brand #3b82f6 3.7:1 白字不达标
--color-success #22c55e 2.3:1 不达标

修法是调色而不是调字号:

1
2
3
4
5
6
:root {
--color-text-secondary: #646a73; /* 5.2:1 */
--color-text-tertiary: #6b7280; /* 4.6:1 */
--color-brand: #2563eb; /* 4.8:1 */
--color-success: #16803c; /* 4.9:1 */
}

设计 token 层加一道 CI 检查:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// scripts/check-contrast.mjs
import { getContrast } from 'color2k'
import tokens from '../tokens.json' assert { type: 'json' }

const PAAIRS = [
['text-primary', 'bg-surface'],
['text-secondary', 'bg-surface'],
['text-tertiary', 'bg-surface'],
['brand-fg', 'brand'],
]

let failed = 0
for (const [fg, bg] of PAAIRS) {
const ratio = getContrast(tokens[fg], tokens[bg])
if (ratio < 4.5) {
console.error(`✗ ${fg} on ${bg}: ${ratio.toFixed(2)}:1`)
failed++
}
}
process.exit(failed ? 1 : 0)

token 改了就跑 CI,避免”某次改主题把对比度改坏了”。

一个真实的收益数据

项目背景:政务后台,2025 年上半年完成工程化改造。

指标 改造前 改造后
测评发现的问题数 47 6
新增页面的 a11y 问题(平均) 8.3 个/页 0.4 个/页
键盘可完整操作的核心流程 60% 100%
改造投入 — 约 6 人日
每次回归的额外耗时 人工走查 30 分钟 CI 自动 40 秒

6 人日的投入换掉一次整改(当时估了 15 人日)+ 长期回归成本,这是我们认为值得的原因。

另一个”意外收益”:组件库的 API 变干净了。因为要把语义做对,很多”靠 div + onClick 拼出来的组件”被迫改成了真实元素,连带的样式和事件处理也更规范了。

踩过的坑

坑 1:aria-hidden 套在有焦点的元素上

1
2
3
<div aria-hidden="true">
<button>这个按钮读屏器看不到,但 Tab 能选中</button>
</div>

结果:键盘用户聚焦到一个”看不见”的位置,完全迷失。规则:aria-hidden 的内容里不能有可聚焦元素(或者配合 inert)。

坑 2:role="button" 不等于 button

1
<div role="button" onClick={fn}>保存</div>

role 只是告诉读屏器”这是什么”,不提供行为。空格键不会触发、不会自动进 Tab 序列。要么用 <button>,要么补齐:

1
2
3
4
5
6
7
8
9
10
11
<div
role="button"
tabIndex={0}
onClick={fn}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
fn()
}
}}
>

这条路永远比直接用 <button> 差。我们的 lint 规则直接禁了 role="button" 挂在非 button 元素上。

坑 3::focus-visible 在某些自定义组件上不生效

用 tabindex="-1" + programmatic focus 的元素(比如路由切换后聚焦到标题),不会触发 :focus-visible。这种场景要显式加 class。

坑 4:CSS 隐藏但保留可访问性,用错方法

1
2
3
4
/* 全部失效:内容读不到 */
display: none;
visibility: hidden;
opacity: 0; /* 读得到,但能 Tab 进去,看不见 */

要”对读屏器可见、视觉隐藏”,只能用 .sr-only 那一套。

坑 5:动画没考虑 prefers-reduced-motion

1
2
3
4
5
6
7
8
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}

这段 CSS 是”成本最低、收益最高”的一行——有前庭功能障碍的用户会因为视差滚动、大范围动效而眩晕。

小结

a11y 工程化的关键不是”多检查”,而是把正确性沉淀到组件里:

  1. 六条组件约束(button 的 type 与焦点、label 关联、dialog 的焦点陷阱、table 的 scope、图标按钮的名称、img 的三种 alt)能消掉 80% 的常见问题。
  2. 四层检查(ESLint 编译期 → 组件单测 → E2E + axe → 键盘走查)覆盖不同阶段,只有最后一层能抓住语义和顺序问题。
  3. 对比度检查接进 CI,避免设计 token 变更悄悄破坏可访问性。
  4. 承认自动化的边界:alt="图片" 这类形式合规比没有更糟,因为它让问题隐形。

最后一句:a11y 的收益不只是”合规”。键盘可操作、焦点清晰、错误可读——这些也是给所有用户的体验提升。

  • 本文标题:可访问性(a11y)工程化:从检查到组件约束
  • 本文作者:MrSmy
  • 创建时间:2025-08-24 20:56:00
  • 本文链接:https://fengyang.live/2025/08/24/可访问性a11y工程化:从检查到组件约束/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!