让图标对屏幕阅读器和辅助技术友好,构建包容性的 Web 体验
区分图标的语义角色是无障碍的第一步:
| 类型 | 定义 | 例子 | 无障碍处理 |
|---|---|---|---|
| 装饰性 | 纯视觉修饰,不传达信息 | 列表前的项目符号图标、分割线旁的装饰图标 | 使用 aria-hidden="true" |
| 功能性 | 传达操作、状态或信息 | 购物车图标、搜索按钮、错误提示 | 添加 aria-label 或 sr-only 文本 |
装饰性图标仅为视觉效果,应被辅助技术隐藏
<!-- 正确:装饰性图标用 aria-hidden 隐藏 -->
<i class="fa-solid fa-star" aria-hidden="true"></i>
<!-- 错误:屏幕阅读器会读出 fa-star 的 Unicode 字符 -->
<i class="fa-solid fa-star"></i>
<!-- 列表前的装饰性图标 -->
<ul class="list-unstyled">
<li><i class="fa-solid fa-check text-success" aria-hidden="true"></i> 已完成</li>
<li><i class="fa-solid fa-circle text-muted" aria-hidden="true"></i> 待办</li>
</ul>当图标本身是交互元素或按钮的唯一标识时:
<!-- 正确:按钮有文字标签,图标装饰性 -->
<button class="btn btn-primary">
<i class="fa-solid fa-cart-shopping" aria-hidden="true"></i> 加入购物车
</button>
<!-- 正确:图标按钮使用 aria-label -->
<button class="btn btn-link" aria-label="搜索">
<i class="fa-solid fa-magnifying-glass" aria-hidden="true"></i>
</button>
<!-- 错误:图标按钮没有可访问名称 -->
<button class="btn btn-link">
<i class="fa-solid fa-magnifying-glass"></i>
</button>SVG 框架自动包含 role="img" 和 aria-labelledby 以提供更好的无障碍支持
<!-- React: 通过 title 属性提供无障碍文本 -->
<FontAwesomeIcon icon={faUser} title="用户信息" />
<!-- 生成的 SVG 会自动包含 role="img" 和 aria-labelledby -->
<!-- <svg role="img" aria-labelledby="svg-title-1">...</svg> -->
<!-- 纯装饰性图标 -->
<FontAwesomeIcon icon={faStar} aria-hidden="true" />
<!-- Vue: 通过 title 或 aria-label 属性 -->
<font-awesome-icon :icon="['fas', 'user']" title="用户信息" />
<font-awesome-icon :icon="['fas', 'star']" aria-hidden="true" />使用 title 属性提供额外上下文
<!-- 使用 title 属性(鼠标悬停显示) -->
<i class="fa-solid fa-circle-info" aria-hidden="true"
title="了解更多信息"></i>
<!-- 使用 sr-only 类(视觉隐藏但可读) -->
<span class="fa-layers">
<i class="fa-solid fa-circle" style="color: #0d6efd;" aria-hidden="true"></i>
<i class="fa-solid fa-check" style="color: white;" aria-hidden="true"></i>
<span class="sr-only">已验证</span>
</span>品牌图标(fa-brands)可能有额外的商标限制
<!-- 品牌图标需要注意商标角色的传达: -->
<a href="https://twitter.com" target="_blank" rel="external nofollow" aria-label="关注我们的 Twitter">
<i class="fa-brands fa-x-twitter" aria-hidden="true"></i>
</a>
<!-- 社交媒体链接列表 -->
<div class="social-links">
<a href="https://github.com/example" aria-label="GitHub">
<i class="fa-brands fa-github" aria-hidden="true"></i>
</a>
<a href="https://weibo.com/example" aria-label="微博">
<i class="fa-brands fa-weibo" aria-hidden="true"></i>
</a>
</div>只有非装饰性图标需要无障碍文本;装饰性图标应使用 aria-hidden
aria-hidden 仅对屏幕阅读器隐藏;图标在屏幕上仍然可见