html - 如何在图形元素之外指定标题
问题描述
我有一种情况,我需要将标题与相关图形物理分开,例如这种标记:
<figure>
<img src="…" alt="…"/>
</figure>
…later in the code…
<figcaption>
Caption text
<figcaption>
这在语义上是不正确的(有解决它的现有 SO 问题),并且会产生验证错误。鉴于此,我想知道表示这一点的适当方式是什么(考虑标记和可访问性)。
理想情况下,会有某种属性(如label
elementsfor
属性)可以让您将 afigcaption
与 a关联起来figure
。目前我正在使用一个aria-describedby
属性(见下文),但我也不确定这是否准确。
<figure aria-describedby="caption">
<img src="…" alt="…"/>
</figure>
…later in the code…
<div id="caption">
Caption text
<div>
解决方案
有几种方法可以解决这个问题,或者通过添加角色和使用aria-labelledby
,或者使用 JavaScript。
方法 1 - 仅 HTML
该aria-labelledby
属性仅在表单控件(例如按钮、输入、复选框等)或已role
分配属性的元素上被识别。如果没有这些条件中的任何一个,将不会在元素上计算可访问名称计算。
<figure role="region" aria-labelledby="caption-text">
<img src="/images/logo.png" alt="your image alt text" />
</figure>
<p>…later in the code…</p>
<div id="caption-text">Caption text</div>
在我对 NVDA/Chrome 的测试中,只要alt
图像上的属性不为空,它就可以工作。我强烈建议在部署到生产环境之前使用不同的浏览器和屏幕阅读器对此进行测试,因为它本质label
上是一个非交互式元素。
方法 2 - JavaScript 和 CSS
此方法更符合您的原始问题。它产生一个非可视figcaption
元素作为元素的子figure
元素。
<style>
.sr-only {
clip: rect(1px, 1px, 1px, 1px);
clip-path: inset(50%);
height: 1px;
width: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
}
</style>
<figure id="fig">
<img src="/images/logo.png" alt="your image alt text" />
</figure>
<p>…later in the code…</p>
<div id="caption-text" aria-hidden="true">Caption text</div>
<script>
document.addEventListener("DOMContentLoaded", () => {
// create a figcaption element
const caption = document.createElement("figcaption")
// get innerText from div#caption-text and add to new figcaption element
caption.innerText = document.getElementById("caption-text").innerText
// assign a class to visually hide
caption.className = "sr-only"
// append figcaption to the figure element
document.getElementById("fig").appendChild(caption)
});
</script>
推荐阅读
- java - 使用dom在Java中创建xml元素和子元素
- javascript - Redux:将参数传递给可以从状态中检索的动作?
- angularjs - 丢失 UI 共享上下文错误 - 在无头 chrome 中运行量角器测试
- python - 嵌套字典和列表的操作
- google-sheets - 使用脚本打印一定范围的 Google 电子表格
- liquibase - 具有不受支持的数据库的 Liquibase
- node.js - 如何创建或更新相同的 DynamoDb 项目?
- python - 在 Python 中从给定的数据文本文件中获取不同的元素
- html - 线性渐变背景覆盖其他元素(例如 img 或 text)
- reactjs - NextJS- How handle redirect, meanwhile my strategy returns an error