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。