Difference between aria-label and aria-labelledby

2019-03-23 11:47发布

I found 2 ways of marking a zone with aria- attributes.

First one:

<div class="main" role="main" aria-label="Search results">
    <a href="">Blah-blah</a>

Second one:

<div class="main" role="main" aria-labelledby="res1">
    <h2 id="res1" class="a11y">Search results</h2>
    <a href="">Blah-blah</a>

JAWS reads them absolutely the same. So, what is the difference and what would you choose?

1条回答
Root(大扎)
2楼-- · 2019-03-23 11:56

This site gives the reason for your answer:-

In theory, you should use aria-labelledby if the text is visually on-screen somewhere and this form is preferable. You should only use aria-label when it’s not possible to have the label visible on screen.

However, with current support, you should always use aria-labelledby, even if you need the label to be hidden. While at least JAWS 12 and VoiceOver both read the aria-label as expected, it turns out that VoiceOver doesn’t correctly read the hierarchy if aria-label is in use. For example:

<p id="group1">Outer group</p>
<p id="item1">First item</p>
<div role="group" aria-labelledby="group1">
<a href="javascript:" role="button" aria-labelledby="item1">Item Content</a>
</div>

everything here is using aria-labelledby and VoiceOver will read the button as “First item Outer group button”. In other words, the button label, the group label and then the type of object.

However, if you change any of the elements to use aria-label, for example:

<p id="item1">First item</p>
<div role="group" aria-label="Outer group">
<a href="javascript:" role="button" aria-labelledby="item1">Item Content</a>
</div>

VoiceOver will now read the button as simple “First item button”. It doesn’t seem to matter which item uses aria-label, if it’s anywhere in the hierarchy, only the label for the button itself will be read out.

From the MDN:-

The aria-labelledby attribute is used to indicate the IDs of the elements that are the labels for the object. It is used to establish a relationship between widgets or groups and their labels. Users of assistive technologies such as screen readers typically navigate a page by tabbing between areas of the screen. If a label is not associated with an input element, widget or group, it will not be read by a screen reader.

And this:-

The aria-label attribute is used to define a string that labels the current element. Use it in cases where a text label is not visible on the screen. (If there is visible text labeling the element, use aria-labelledby instead.)

查看更多
登录 后发表回答