實現一個鍵盤可操作的下拉選單元件,支援:
<div class="autocomplete" role="combobox" aria-expanded="false" aria-haspopup="listbox" aria-owns="options-list">
<label for="search-input" class="visually-hidden">搜尋電影類型</label>
<input
type="text"
id="search-input"
class="autocomplete-input"
autocomplete="off"
aria-autocomplete="list"
aria-controls="options-list"
aria-activedescendant=""
placeholder="輸入電影類型..."
>
<ul id="options-list" class="autocomplete-options" role="listbox" aria-label="電影類型選項">
<li role="option" id="opt-0" data-value="科幻片">科幻片</li>
<li role="option" id="opt-1" data-value="戰爭片">戰爭片</li>
<li role="option" id="opt-2" data-value="動作片">動作片</li>
<li role="option" id="opt-3" data-value="愛情片">愛情片</li>
<li role="option" id="opt-4" data-value="劇情片">劇情片</li>
<li role="option" id="opt-5" data-value="記錄片">記錄片</li>
<li role="option" id="opt-6" data-value="綜藝片">綜藝片</li>
<li role="option" id="opt-7" data-value="喜劇片">喜劇片</li>
<li role="option" id="opt-8" data-value="動畫片">動畫片</li>
<li role="option" id="opt-9" data-value="勵志片">勵志片</li>
<li role="option" id="opt-10" data-value="恐怖片">恐怖片</li>
<li role="option" id="opt-11" data-value="古裝片">古裝片</li>
<li role="option" id="opt-12" data-value="電視劇">電視劇</li>
<li role="option" id="opt-13" data-value="讀書">讀書</li>
<li role="option" id="opt-14" data-value="小說">小說</li>
<li role="option" id="opt-15" data-value="作品集">作品集</li>
<li role="option" id="opt-16" data-value="歷史">歷史</li>
<li role="option" id="opt-17" data-value="詩歌">詩歌</li>
<li role="option" id="opt-18" data-value="散文">散文</li>
<li role="option" id="opt-19" data-value="軍事">軍事</li>
</ul>
</div>
.autocomplete { position: relative; width: 300px; font-family: system-ui, sans-serif; }
.autocomplete-input {
width: 100%; padding: 10px 12px; font-size: 16px;
border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box;
}
.autocomplete-input:focus { outline: none; border-color: #3498db; box-shadow: 0 0 0 3px rgba(52,152,219,0.2); }
.autocomplete-options {
position: absolute; top: 100%; left: 0; right: 0; margin-top: 4px;
background: #fff; border: 1px solid #ddd; border-radius: 4px;
box-shadow: 0 4px 12px rgba(0,0,0,0.1); max-height: 280px; overflow-y: auto;
list-style: none; padding: 4px 0; z-index: 100; display: none;
}
.autocomplete-options[aria-hidden="false"] { display: block; }
.autocomplete-options[aria-hidden="true"] { display: none; }
.autocomplete-options li {
padding: 10px 12px; cursor: pointer; white-space: nowrap;
transition: background 0.1s;
}
.autocomplete-options li[aria-selected="true"] {
background: #3498db; color: #fff;
}
.autocomplete-options li:hover { background: #f0f0f0; }
.autocomplete-options li[aria-selected="true"]:hover { background: #2980b9; }
class Autocomplete {
constructor(container) {
this.container = container;
this.input = container.querySelector(".autocomplete-input");
this.listbox = container.querySelector(".autocomplete-options");
this.options = Array.from(this.listbox.querySelectorAll('[role="option"]'));
this.activeIndex = -1;
this.filteredOptions = this.options;
this.isOpen = false;
this.bindEvents();
this.initARIA();
}
initARIA() {
this.listbox.setAttribute("aria-hidden", "true");
this.options.forEach((opt, i) => {
opt.setAttribute("aria-selected", "false");
opt.id = opt.id || `opt-${i}`;
});
}
bindEvents() {
// 輸入過濾
this.input.addEventListener("input", () => this.filter(this.input.value));
// 鍵盤導航
this.input.addEventListener("keydown", (e) => this.handleKeydown(e));
// 滑鼠點擊選項
this.listbox.addEventListener("click", (e) => {
const option = e.target.closest('[role="option"]');
if (option) this.selectOption(option);
});
// 滑鼠懸停高亮(同步 activeIndex)
this.listbox.addEventListener("mouseover", (e) => {
const option = e.target.closest('[role="option"]');
if (option) this.setActive(option);
});
// 點擊外部關閉
document.addEventListener("click", (e) => {
if (!this.container.contains(e.target)) this.close();
});
// 焦點管理
this.input.addEventListener("focus", () => {
if (this.filteredOptions.length) this.open();
});
this.input.addEventListener("blur", () => {
// 延遲關閉,讓點擊選項的 click 事件先觸發
setTimeout(() => this.close(), 150);
});
}
filter(query) {
const lower = query.toLowerCase();
this.filteredOptions = this.options.filter(opt =>
opt.textContent.toLowerCase().includes(lower)
);
this.options.forEach(opt => {
const isMatch = this.filteredOptions.includes(opt);
opt.style.display = isMatch ? "" : "none";
if (!isMatch) opt.setAttribute("aria-selected", "false");
});
this.activeIndex = -1;
this.updateActiveDescendant();
if (this.filteredOptions.length) this.open(); else this.close();
}
handleKeydown(e) {
const { key } = e;
const visibleOptions = this.filteredOptions.filter(o => o.style.display !== "none");
switch (key) {
case "ArrowDown":
e.preventDefault();
this.moveFocus(1, visibleOptions);
break;
case "ArrowUp":
e.preventDefault();
this.moveFocus(-1, visibleOptions);
break;
case "ArrowRight":
e.preventDefault();
// 網格佈局:向右移動(需知道每行項目數)
this.moveFocus(this.getCols(), visibleOptions);
break;
case "ArrowLeft":
e.preventDefault();
this.moveFocus(-this.getCols(), visibleOptions);
break;
case "Enter":
if (this.activeIndex >= 0 && visibleOptions[this.activeIndex]) {
e.preventDefault();
this.selectOption(visibleOptions[this.activeIndex]);
}
break;
case "Escape":
this.close();
this.input.blur();
break;
case "Tab":
this.close();
break;
}
}
getCols() {
// 簡易估算:容器寬度 / 選項寬度
return Math.max(1, Math.floor(this.listbox.offsetWidth / 120));
}
moveFocus(delta, visibleOptions) {
if (!visibleOptions.length) return;
let newIndex = this.activeIndex + delta;
if (newIndex < 0) newIndex = visibleOptions.length - 1;
if (newIndex >= visibleOptions.length) newIndex = 0;
this.setActive(visibleOptions[newIndex]);
}
setActive(option) {
// 移除舊 active
this.listbox.querySelector('[aria-selected="true"]')?.setAttribute("aria-selected", "false");
// 設置新 active
option.setAttribute("aria-selected", "true");
this.activeIndex = this.filteredOptions.indexOf(option);
this.updateActiveDescendant();
this.scrollIntoView(option);
}
updateActiveDescendant() {
const activeOption = this.filteredOptions[this.activeIndex];
this.input.setAttribute("aria-activedescendant", activeOption?.id || "");
}
scrollIntoView(option) {
const listbox = this.listbox;
const optionTop = option.offsetTop;
const optionBottom = optionTop + option.offsetHeight;
const scrollTop = listbox.scrollTop;
const clientHeight = listbox.clientHeight;
if (optionTop < scrollTop) listbox.scrollTop = optionTop;
else if (optionBottom > scrollTop + clientHeight) listbox.scrollTop = optionBottom - clientHeight;
}
selectOption(option) {
this.input.value = option.textContent;
this.input.setAttribute("aria-activedescendant", "");
this.close();
// 觸發自定義事件
this.container.dispatchEvent(new CustomEvent("select", {
detail: { value: option.dataset.value, text: option.textContent }
}));
}
open() {
if (this.isOpen) return;
this.isOpen = true;
this.listbox.setAttribute("aria-hidden", "false");
this.container.setAttribute("aria-expanded", "true");
}
close() {
if (!this.isOpen) return;
this.isOpen = false;
this.listbox.setAttribute("aria-hidden", "true");
this.container.setAttribute("aria-expanded", "false");
this.activeIndex = -1;
this.updateActiveDescendant();
}
}
// 初始化
document.addEventListener("DOMContentLoaded", () => {
document.querySelectorAll(".autocomplete").forEach(el => new Autocomplete(el));
// 監聽選擇事件
document.querySelectorAll(".autocomplete").forEach(el => {
el.addEventListener("select", (e) => console.log("選擇:", e.detail));
});
});
原始碼中 case 38 (Up): index -= 4、case 40 (Down): index += 4 假設每行 4 個選項。現代實作應動態計算每行列數:
getCols() {
const firstOption = this.listbox.querySelector('[role="option"]:not([style*="display: none"])');
if (!firstOption) return 1;
const optionWidth = firstOption.offsetWidth;
const gap = parseInt(getComputedStyle(this.listbox).gap) || 0;
return Math.max(1, Math.floor((this.listbox.clientWidth + gap) / (optionWidth + gap)));
}
| 準則 | 實作 | 驗證方式 |
|---|---|---|
| 1.3.1 資訊與關係 | role="combobox" + aria-controls + aria-owns | axe-core、WAVE |
| 2.1.1 鍵盤操作 | ↑↓←→ Enter Esc Tab 全支援 | 斷開滑鼠純鍵盤操作 |
| 2.4.3 焦點順序 | 焦點停留在 input,選項用 aria-activedescendant | Tab 鍵導航測試 |
| 4.1.2 名稱、角色、值 | role="option"、aria-selected、aria-activedescendant | 螢幕閱讀器 (NVDA/VoiceOver) 測試 |
| 1.4.3 對比度 | 選中狀態 白字藍底 4.5:1+ | Color Contrast Analyzer |
鍵盤可操作的下拉選單是無障礙網頁的核心元件。關鍵在於:焦點停留在輸入框(不移至選項)、使用 aria-activedescendant 指向當前高亮選項、aria-expanded/aria-hidden 控制面板可見性、方向鍵支援單行與網格兩種佈局。此架構可擴展為完整的 Autocomplete/Combobox/Select 元件庫基礎。