ElementInternals: ariaLabelledByElements 属性
ElementInternals
接口的 ariaLabelledByElements
属性是一个数组,其中包含为应用该属性的元素提供可访问名称的元素(一个或多个)。
该属性主要用于为没有标准方法来定义其可访问名称的元素提供标签。例如,它可以用于命名一个通用的容器元素,如 <div>
或 <span>
,或者一组元素,例如带有用于更改其不透明度的滑块的图片。该属性的优先级高于其他提供元素可访问名称的机制,因此也可以用于为通常会从其内部内容或关联元素(如 label)获取可访问名称的元素提供名称。
aria-labelledby
主题包含有关如何使用该属性和特性的更多信息。
值
一个元素数组。这些元素的内部文本可以与空格连接起来以获得可访问名称。
读取时,返回的数组是静态的且只读的。写入时,将复制分配的数组:之后对数组的更改不会影响属性的值。
描述
该属性是使用 aria-labelledby
属性来设置可访问名称的一种灵活替代方案。与 aria-labelledby
不同,分配给此属性的元素不必具有 id
属性。
当定义了元素的 aria-labelledby
属性时,该属性会反映该属性,但仅限于列出的引用 id
值与有效的范围内元素匹配的情况。如果设置了该属性,则会清除相应的属性。有关反映的元素引用和作用域的更多信息,请参阅Reflected attributes 指南中的 Reflected element references。
示例
获取可访问名称
此示例演示了如何使用 ariaLabelledByElements
以编程方式获取在 shadow root 中使用 aria-labelledby
定义的标签。
HTML
HTML 定义了两个 <span>
元素,并在 <input>
的 aria-labelledby
属性中引用了它们的 id。因此,<input>
的可访问名称是两个被引用元素内部文本的连接。
<div id="host">
<template shadowrootmode="open">
<span id="label_1">Street name</span>
<input aria-labelledby="label_1 label_2" />
<span id="label_2">(just the name, no "Street" or "Road" or "Place")</span>
</template>
</div>
JavaScript
下面的代码首先检查是否支持 ariaLabelledByElements
,如果不支持,则记录结果并退出。如果支持该属性,则首先记录该属性的值。然后,它会遍历返回的元素,连接它们的内部文本,并记录元素的最终可访问名称。
// Get access to the input within shadowRoot
const hostElement = document.getElementById("host");
const shadowRoot = hostElement.shadowRoot;
const inputElement = shadowRoot.querySelector("input");
// Feature test for ariaLabelledByElements
if ("ariaLabelledByElements" in ElementInternals.prototype) {
// Get and log attribute that provides the accessible name
log(`aria-labelledby: ${inputElement.getAttribute("aria-labelledby")}`);
// Get and log elements that provide the accessible name
const labelElements = inputElement.ariaLabelledByElements;
log(`ariaLabelledByElements: ${labelElements}`);
// Log inner text of elements to get accessible name
const text = labelElements.map((e) => e.textContent.trim()).join(" ");
log(`Accessible name: ${text.trim()}`);
} else {
log("ariaLabelledByElements not supported by browser");
}
结果
下面的日志显示了上述代码的输出。这应该显示被引用 HTMLSpanElement
元素的数组,以及由它们的内部文本组成的最终可访问名称。
规范
规范 |
---|
无障碍富互联网应用程序 (WAI-ARIA) # dom-ariamixin-arialabelledbyelements |
浏览器兼容性
加载中…
另见
aria-labelledby
属性Element.ariaLabelledByElements
- Attribute reflection 指南中的Reflected element references。