在跨度上使用 aria-label

Dan*_*ich 3 html ios voiceover wai-aria

我正在使用 Unicode 星号显示产品评级。iOS VoiceOver 无法正确朗读此内容,因此我想我会aria-label在我的跨度上使用它来告诉屏幕阅读器它的含义。

<span aria-label="4.0 stars out of 5, 123 ratings">????? 4.0 (123)</span>
Run Code Online (Sandbox Code Playgroud)

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

我究竟做错了什么?我怎样才能解决这个问题?

slu*_*ous 9

aria-label如果您放置的元素没有任何语义含义,则有时会被某些辅助技术忽略。<span> 没有语义。如果您添加了role适合您的星星,则应该正确阅读。


Abd*_*ull 5

引用mdn web docaria-label文章

\n
\n

并非所有元素都可以被赋予可访问的名称。aria-label 和 aria-labelledby 都不应与非交互式元素或内联结构角色(例如代码、术语或强调)一起使用,也不应与语义不会映射到辅助功能 API 的角色一起使用,包括presentation、none 和hidden。aria-label 属性仅适用于交互元素。

\n
\n

这就是为什么aria-label对元素没有影响<span><span>是一个没有语义的非交互式元素。

\n

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

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

重用Bootstrap 5 的.visually-hiddenCSS 类,您的示例可以重写如下:

\n

\r\n
\r\n
.visually-hidden {\n    position: absolute !important;\n    width: 1px !important;\n    height: 1px !important;\n    padding: 0 !important;\n    margin: -1px !important;\n    overflow: hidden !important;\n    clip: rect(0,0,0,0) !important;\n    white-space: nowrap !important;\n    border: 0 !important;\n}
Run Code Online (Sandbox Code Playgroud)\r\n
<span aria-hidden="true">\xe2\x98\x85\xe2\x98\x85\xe2\x98\x85\xe2\x98\x85\xe2\x98\x86 4.0 (123)</span>\n<span class="visually-hidden">4.0 stars out of 5, 123 ratings</span>
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n

    \n
  • 从视觉上看,这只会显示“4 个黑色 Unicode 星号、1 个白色 Unicode 星号、4.0和括号中的123 ”。
  • \n
  • 对于屏幕阅读器,这只会显示4.0 颗星(满分 5 颗星,123 个评分) ”。
  • \n
\n