在跨度上使用 aria-label

Use aria-label on a span

我正在使用 Unicode 星号显示产品评级。 iOS VoiceOver 没有正确地大声朗读,所以我想我应该在我的 span 上使用 aria-label 来告诉屏幕阅读器它的意思。

<span aria-label="4.0 stars out of 5, 123 ratings">★★★★☆ 4.0 (123)</span>

它不起作用。 iOS VoiceOver 完全忽略了我的 aria-label

我做错了什么?我该如何解决这个问题?

一种方法是添加 role=img

<span aria-label="4.0 stars out of 5, 123 ratings" role="img">★★★★☆ 4.0 (123)</span>

如果您放置的元素没有任何语义意义,aria-label 有时会被某些辅助技术忽略。 没有语义。如果你添加一个适合你的星星的role,那么它应该被正确读取。

引用 mdn web doc's aria-label article:

Not all elements can be given an accessible name. Neither aria-label nor aria-labelledby should be used with non-interactive elements or inline structural role such as with code, term, or emphasis nor roles whose semantics will not be mapped to the accessibility API, including presentation, none, and hidden. The aria-label attribute is intended for interactive elements only.

所以这就是 aria-label<span> 元素没有影响的原因:<span> 是一个没有语义的 non-interactive 元素。

但您可以这样做:提供两个 <span>,每个表达相同的信息,但针对不同的“目标群体”:

  • 一个<span>是视觉no-screenreader版本;属性 aria-hidden="true" 将确保它不会成为 辅助功能树 的一部分,因此屏幕阅读器不会将其传达给用户。
  • 一个 <span> 是可访问的屏幕阅读器版本:CSS 样式负责视觉上 隐藏它。

重用Bootstrap 5's .visually-hidden CSS class,您的示例可以这样重写:

.visually-hidden {
    position: absolute !important;
    width: 1px !important;
    height: 1px !important;
    padding: 0 !important;
    margin: -1px !important;
    overflow: hidden !important;
    clip: rect(0,0,0,0) !important;
    white-space: nowrap !important;
    border: 0 !important;
}
<span aria-hidden="true">★★★★☆ 4.0 (123)</span>
<span class="visually-hidden">4.0 stars out of 5, 123 ratings</span>

  • 在视觉上,这将 呈现“4 个黑色 Unicode 星号、1 个白色 Unicode 星号、4.0 123 括号内.
  • 对于屏幕阅读器,这将显示“4.0 颗星,满分 5 颗星,123 个评分”。