label id 和 aria-labelledby 之间的区别用法

difference usage between label id and aria-labelledby

我知道 aria-label 和 aria-labelledby 之间的区别,但是下面这些之间有什么区别,什么时候互相使用?

代码来自react-testing-library

// first
<label for="username-input">Username</label>
<input id="username-input" />

// second
<label id="username-label">Username</label>
<input aria-labelledby="username-label" />

对于第一个,根据mdn documentation

The label text is not only visually associated with its corresponding text input; it is programmatically associated with it too. ... You can click the associated label to focus/activate the input, as well as the input itself.

但是第二个不为浏览器用户提供该功能,因为它只是可访问性的 ARIA 属性。

我还检查了 chrome devtools - 可访问性,我发现 first 和 second 的计算属性都显示输入和标签相互关联。

据我了解,第一个为用户提供编程访问权限,第二个则没有,第一个和第二个都可以通过屏幕 reader 正确访问。

第二个是第一个的子集吗?那么下面的代码是不是无效模式,因为第一个是第二个的超集?

<label id="username-label" for="username-input">Username</label>
<input id="username-input" aria-labelledby="username-label" />

谢谢。

我对 aria-labelaria-labelledBy 之间的主要区别的一些描述。

Use aria-label if label text is not visible on the screen and use aria-labelledBy if label text is visible.

如果需要,我们可以阅读更多关于 aria 属性 here 的用例。

label id 和 aria-labelledby 的用法区别

// first
<label for="username-input">Username</label>
<input id="username-input" />

// second
<label id="username-label">Username</label>
<input aria-labelledby="username-label" />

第一个是将表单标签与输入相关联的合法或传统方式。第二个在点击相关标签时不提供焦点输入功能。它仅用于 Web 可访问性。第一个不仅提供 Web 可访问性,还提供焦点输入功能。所以,我们可以说第一个比第二个更强大。

还有两种方法可以将标签与输入以及输入焦点功能相关联。

// Wrapper labels
<label>Username <input /></label>

// Wrapper labels where the label text is in another child element
<label>
  <span>Username</span>
  <input />
</label>

还有一种方法可以将 invisible or hidden 标签与输入相关联,但不提供焦点输入功能。

// aria-label attributes
// Take care because this is not a label that users can see on the page,
// so the purpose of your input must be obvious to visual users.
<input aria-label="Username" />

我在工作场所有一些(我的)规则。

  • I use the first example always whenever it's possible.
  • I use aria-label when I have don't have visible text. Imagine a form with an input element that doesn't have a label associated with it and placeholder text for giving information on what to put in the input.
  • I use aria-labelledBy to associated non-label elements with the interactive elements (eg: Input)

第二个是第一个的子集吗?那么下面的代码无效模式是因为第一个是第二个的超集吗?

<label id="username-label" for="username-input">Username</label>
<input id="username-input" aria-labelledby="username-label" />

我们必须知道将标签与输入相关联的主要优点是什么。一个是您在问题中提到的 web accessibility 另一个是(根据 mdn docs

You can click the associated label to focus/activate the input, as well as the input itself. This increased hit area provides an advantage to anyone trying to activate the input, including those using a touch-screen device.

从这个模式中,您将标签与输入相关联两次,一次用于焦点输入功能。第一个确实同时提供了这两个功能,因此在标签和输入之间再添加一个关联性是没有意义的。