标签 id 和 aria-labelledby 之间的差异用法

jwk*_*koo 5 html label wai-aria

我知道 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" />
Run Code Online (Sandbox Code Playgroud)

对于第一个,根据mdn文档

标签文本不仅在视觉上与其相应的文本输入相关联,而且在视觉上也与其相应的文本输入相关联。它也以编程方式与之关联。...您可以单击关联的标签来聚焦/激活输入以及输入本身。

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

我还检查了 chrome devtools - accessiblity,我发现第一个和第二个的计算属性都显示输入和标签彼此关联。

因此,据我了解,第一个为用户提供了编程访问权限,但第二个没有,并且屏幕阅读器可以正确访问第一个和第二个。

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

<label id="username-label" for="username-input">Username</label>
<input id="username-input" aria-labelledby="username-label" />
Run Code Online (Sandbox Code Playgroud)

谢谢。

Sub*_*aik 4

aria-label对我这边和我这边的主要区别进行一些描述aria-labelledBy

aria-label如果标签文本在屏幕上不可见,则使用;如果aria-labelledBy标签文本可见,则使用。

如果需要,我们可以在此处阅读有关 aria 属性的用例的更多信息。

标签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" />
Run Code Online (Sandbox Code Playgroud)

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

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

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

// Wrapper labels where the label text is in another child element
<label>
  <span>Username</span>
  <input />
</label>
Run Code Online (Sandbox Code Playgroud)

还有另一种方法可以将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" />
Run Code Online (Sandbox Code Playgroud)

我在工作场所使用了一些(我的)规则。

  • 只要有可能,我总是使用第一个例子。
  • aria-label当我没有可见文本时我会使用它。想象一个带有输入元素的表单,该元素没有与之关联的标签,也没有用于提供有关输入内容的信息的占位符文本。
  • 我习惯aria-labelledBy将非标签元素与交互元素相关联(例如:输入)

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

<label id="username-label" for="username-input">Username</label>
<input id="username-input" aria-labelledby="username-label" />
Run Code Online (Sandbox Code Playgroud)

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

您可以单击关联的标签来聚焦/激活输入以及输入本身。这种增加的点击区域为任何试图激活输入的人提供了优势,包括那些使用触摸屏设备的人。

在此模式中,您将标签与输入关联两次,一次用于焦点输入功能。第一个确实同时提供了这两种功能,因此没有必要在标签和输入之间添加更多关联性。