html - 如何在图形元素之外指定标题

标签 html accessibility figure figcaption

我遇到一种情况,我需要在物理上将标题与关联的图形分开,例如这种标记:

<figure>
  <img src="…" alt="…"/>
</figure>

…later in the code…

<figcaption>
  Caption text
<figcaption>

这在语义上不正确( there are existing SO questions addressing it ),并且会产生验证错误。鉴于此,我想知道表示这一点的适当方法是什么(考虑标记和可访问性)。

理想情况下,会有某种属性(例如 label 元素 for 属性)让您将 figcaption。目前我正在使用 aria-scribedby 属性(见下文),但我也不确定这是否准确。

<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 属性的元素上被识别。如果没有这些条件,accessible name computation不会对元素进行计算。

<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 属性不为空,此功能就有效。我强烈建议在部署到生产环境之前使用不同的浏览器和屏幕阅读器对其进行测试,因为它本质上是非交互式元素上的标签

方法 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>

关于html - 如何在图形元素之外指定标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69211525/

相关文章:

javascript - Ajax 表单提交设置 enctype

python - 如何使用pylab远程保存图形?

matlab - 在 Matlab 中保存裁剪图

latex - 如何将图形放置在 latex 中的页面底部?

html - 如何使所有屏幕分辨率的垂直菜单居中?

jquery - 使用 div 自己的无限滚动

javascript - 错误: 508 (Loop detected)

html - 无需电子邮件地址即可访问 mailto 链接

javascript - 在链接中添加 span 元素,使其可通过 javascript 访问 (AA)

jquery - 可访问的全宽下拉菜单,具有 Jquery 悬停、焦点和模糊功能