简体   繁体   中英

Use aria-label on a span

I'm showing product ratings using Unicode star symbols. iOS VoiceOver doesn't read this aloud correctly, so I thought I'd use aria-label on my span to tell screen readers what it means.

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

It's not working. iOS VoiceOver ignores my aria-label completely.

What am I doing wrong? How can I fix this?

The aria-label is sometimes ignored by some assistive technology if the element you put it on doesn't have any semantic meaning. A <span> doesn't have semantic meaning. If you add a role that is appropriate for your stars, then it should be read correctly.

一种方法是添加role=img

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

Quoting 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.

So that's why aria-label has no effect on <span> elements: <span> is a non-interactive element without semantics.

But here is what you can do: provide two <span> s, each expressing the same information but for separate "target groups":

  • One <span> is the visual no-screenreader version; the attribute aria-hidden="true" will make sure it will not be part of the accessibility tree and therefore not be communicated by screen readers to their users.
  • One <span> is the accessible screenreader version: CSS styling takes care of visually hiding it.

Reusing Bootstrap 5's .visually-hidden CSS class , your example can be rewritten like so:

 .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>

  • Visually, this will only present "4 black Unicode stars, 1 white Unicode star, 4.0 , and 123 in parentheses".
  • For screen readers, this will only present " 4.0 stars out of 5, 123 ratings ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM