PageSpeed Insights 在我们的网站上抱怨“表单元素没有关联的标签”。
我使用的相关代码是:
<input id="input-1" type="checkbox">
<label for="input-1">
<svg>
<title>This is the label text</title>
<!-- rest of svg -->
</svg>
</label>
这应该足够方便吗? (我知道使用没有文本的 SVG 图标对于有视力的用户来说并不是最佳的可访问性,但这不是 PageSpeed 在这里抱怨的。)
可访问名称和描述计算标准中的计算步骤特别提到
<title>
元素作为为标签提供文本的有效方式。
E。主机语言标签:否则,如果当前节点的本机标记提供了定义文本替代项的属性(例如 alt)或元素(例如 HTML 标签或 SVG
),则以平面字符串的形式返回该替代项由宿主语言定义,除非该元素被标记为表示性的(role="presentation" 或 role="none")。title
(我强调了重要的部分)
所以说到一致性,你很好。
但是,对于可访问性来说重要的也是实用部分。有多少用户因浏览器或辅助技术支持不足而遇到困难?你绝对应该测试一下。
根据 a11y 支持,SVG
<title>
元素在 iOS 上的 VoiceOver 中不支持,在 macOS 上仅部分支持。我可以确认它仍然是 Firefox 中的问题。
我建议使用
aria-label
或视觉上隐藏的元素来为 SVG 图标提供替代文本。
/* https://www.scottohara.me/blog/2017/04/14/inclusively-hidden.html */
.visually-hidden:not(:focus):not(:active) {
clip: rect(0 0 0 0);
clip-path: inset(50%);
height: 1px;
overflow: hidden;
position: absolute;
white-space: nowrap;
width: 1px;
}
<input id="input-1" type="checkbox">
<label for="input-1">
<svg aria-label="This is the label text" data-altlabel="svg-title" width="50" height="50">
<title id="svg-title">This is the label text</title>
<!-- rest of svg -->
<rect width="50" height="50" fill="#cc0000"></rect>
</svg>
</label>
<input id="input-2" type="checkbox">
<label for="input-2">
<span class="visually-hidden">This is the label text</span>
<svg aria-hidden="true" width="50" height="50">
<!-- rest of svg -->
<rect width="50" height="50" fill="#cc0000"></rect>
</svg>
</label>