Element: ariaControlsElements 屬性
Element 介面的 ariaControlsElements 屬性是一個數組,其中包含由應用此屬性的元素所控制的元素。例如,這可以設定在 combobox 上,以指示它彈出的元素,或者設定在 scrollbar 上,以指示它控制的元素的 ID。
有關如何使用該屬性和特性的更多資訊,請參閱 aria-controls 主題。
值
一個 HTMLElement 的子類陣列,表示由該元素控制的元素。
讀取時,返回的陣列是靜態的且只讀的。寫入時,會複製分配的陣列:後續對陣列的更改不會影響該屬性的值。
描述
該屬性是使用 aria-controls 屬性設定被控制元素的靈活替代方案。與 aria-controls 不同,分配給此屬性的元素不必具有 id 屬性。
當 aria-controls 屬性定義時,該屬性會反映它,但僅限於列出的、與有效的範圍內元素匹配的 ID 值。如果設定了該屬性,則相應的屬性將被清除。有關反映的元素引用和範圍的更多資訊,請參閱 _Reflected attributes_ 指南中的 Reflected element references。
示例
獲取被控制的元素
此示例顯示瞭如何使用 ariaControlsElements 來獲取使用 aria-controls 設定的被控制元素。
HTML
HTML 首先定義了一個 <button> 元素和兩個它所控制的 <div> 元素,panel1 和 panel2。對被控制面板的引用列在按鈕的 aria-controls 屬性中。
<button id="toggleButton" aria-controls="panel1 panel2" aria-expanded="false">
Show Details
</button>
<div class="panel" id="panel1" aria-hidden="true">
<p>Panel1 opened/closed by button.</p>
</div>
<div class="panel" id="panel2" aria-hidden="true">
<p>Panel2 opened/closed by button.</p>
</div>
.panel {
display: none; /* Initially hidden */
border: 1px solid #cccccc;
padding: 5px;
margin-top: 5px;
}
JavaScript
程式碼首先根據按鈕的 aria-expanded 屬性來設定面板的開啟或隱藏。
const toggleButton = document.querySelector("#toggleButton");
const panel1 = document.querySelector("#panel1");
const panel2 = document.querySelector("#panel2");
toggleButton.addEventListener("click", () => {
const isExpanded = toggleButton.getAttribute("aria-expanded") === "true";
toggleButton.setAttribute("aria-expanded", !isExpanded);
panel1.style.display = isExpanded ? "none" : "block";
panel1.setAttribute("aria-hidden", isExpanded); // true when hidden, false when shown.
panel2.style.display = isExpanded ? "none" : "block";
panel2.setAttribute("aria-hidden", isExpanded); // true when hidden, false when shown.
});
接下來,示例使用 Element.getAttribute() 獲取 aria-controls 屬性的值(一個列出被引用元素 ID 的字串)。然後,它檢查 ariaControlsElements 屬性是否受支援,如果支援,則記錄其值。最後,它返回並記錄每個被控制元素的內部文字。
log(`aria-controls: ${toggleButton.getAttribute("aria-controls")}`);
// Feature test for ariaControlsElements
if ("ariaControlsElements" in Element.prototype) {
// Get ariaControlsElements
const controlledElements = toggleButton.ariaControlsElements;
log(`ariaControlsElements: ${controlledElements}`);
// List innerText for each of the ariaControlsElements
controlledElements.forEach((controlled) => {
log(` Controlled element text: ${controlled.textContent.trim()}`);
});
} else {
log("element.ariaControlsElements: not supported by browser");
}
結果
點選下面的按鈕來顯示和隱藏面板。日誌顯示原始元素引用、關聯/返回的元素以及每個元素的內部文字。
規範
| 規範 |
|---|
| 無障礙富網際網路應用程式 (WAI-ARIA) # dom-ariamixin-ariacontrolselements |
瀏覽器相容性
載入中…
另見
aria-controls屬性ElementInternals.ariaControlsElements- Attribute reflection 指南中的 Reflected element references