首页 > 解决方案 > 如何在图形元素之外指定标题

问题描述

我有一种情况,我需要将标题与相关图形物理分开,例如这种标记:

<figure>
  <img src="…&quot; alt="…&quot;/>
</figure>

…later in the code…

<figcaption>
  Caption text
<figcaption>

这在语义上是不正确的(有解决它的现有 SO 问题),并且会产生验证错误。鉴于此,我想知道表示这一点的适当方式是什么(考虑标记和可访问性)。

理想情况下,会有某种属性(如labelelementsfor属性)可以让您将 afigcaption与 a关联起来figure。目前我正在使用一个aria-describedby属性(见下文),但我也不确定这是否准确。

<figure aria-describedby="caption">
  <img src="…&quot; alt="…&quot;/>
</figure>

…later in the code…

<div id="caption">
  Caption text
<div>

标签: htmlaccessibilityfigurefigcaption

解决方案


有几种方法可以解决这个问题,或者通过添加角色和使用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…&lt;/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…&lt;/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>

推荐阅读