Element:ariaLabelledByElements 属性
Element
接口的 ariaLabelledByElements
属性是一个数组,其中包含为应用该属性的元素提供可访问名称的元素(一个或多个)。
该属性主要用于为没有标准方法来定义其可访问名称的元素提供标签。例如,它可以用于命名一个通用的容器元素,如 <div>
或 <span>
,或者一组元素,例如一个图片以及一个用于改变其不透明度的滑块。该属性优先于其他提供元素可访问名称的机制,因此也可以用于为通常从其内部内容或关联元素(如 <label>
)获取名称的元素提供名称。
aria-labelledby
主题包含有关如何使用该属性和属性的更多信息。
值
一个元素数组。这些元素的内部文本可以与空格连接起来以获得可访问名称。
读取时,返回的数组是静态的且只读的。写入时,将复制分配的数组:之后对数组的更改不会影响属性的值。
描述
该属性是使用 aria-labelledby
属性来设置可访问名称的一种灵活替代方案。与 aria-labelledby
不同,分配给此属性的元素不必具有 id
属性。
当 aria-labelledby
属性已定义时,此属性会反映该属性,但仅限于列出的引用 id
值,这些值匹配有效的范围内的元素。如果设置了该属性,则相应的属性将被清除。有关反射的元素引用和范围的更多信息,请参阅Attribute reflection指南中的Reflected element references。
示例
获取可访问名称
此示例显示了如何使用 ariaLabelledByElements
来获取使用 aria-labelledby
定义的 ARIA 标签。
HTML
HTML 定义了两个 <span>
元素,并在 <input>
的 aria-labelledby
属性中引用了它们的 id。<input>
的可访问名称是两个引用元素内部文本的连接,中间用空格分隔。
<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>
JavaScript
下面的代码首先使用 Element.getAttribute()
(列出引用元素 id
值的字符串) 记录 aria-labelledby
属性的值。然后它检查 ariaLabelledByElements
是否受支持,如果受支持,则记录其值。最后,它通过迭代元素并连接它们的内部文本来计算并返回可访问字符串。
const inputElement = document.querySelector("input");
log(`aria-labelledby: ${inputElement.getAttribute("aria-labelledby")}`);
// Feature test for ariaLabelledByElements
if ("ariaLabelledByElements" in Element.prototype) {
// Get ariaLabelledByElements
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("element.ariaLabelledByElements: not supported by browser");
}
结果
下面的日志显示了原始元素引用、关联/返回的元素以及可访问名称。请注意,该示例不对输入到街道名称 <input>
中的文本做任何处理。
规范
规范 |
---|
无障碍富互联网应用程序 (WAI-ARIA) # dom-ariamixin-arialabelledbyelements |
浏览器兼容性
加载中…
另见
aria-labelledby
属性ElementInternals.ariaLabelledByElements
- Attribute reflection 指南中的Reflected element references。