实现说明
除了函数 next、focusAt,文件里再无其他定义。
for (const [i, item] of options.entries()) 是唯一的迭代点——其余代码顺序执行一遍。
使用要点
- 用到了
document,需要在浏览器环境运行,Node 里直接跑会缺 API。 - 直接运行文件,输出会带上标签,比如
tabbable option:、after arrow down, focused:——输出的每一行都能指回产生它的那次调用。
常见问题
「roving tabindex 键盘导航」能在裸 Node.js 里跑吗?
不能——document 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。
主签名形如 const next = (index + options.length)
核心语句
const options: HTMLLIElement[] = items.map((label, index) => {
const li = document.createElement('li');
li.setAttribute('role', 'option');
li.textContent = label;
li.tabIndex = index === 0 ? 0 : -1;
list.append(li);
return li;
});
代码示例
// Roving tabindex pattern for keyboard navigation: exactly one item is
// tabbable, arrow keys move focus between options, the rest stay at -1
const items = ['Cut', 'Copy', 'Paste', 'Delete'];
const list = document.createElement('ul');
list.setAttribute('role', 'listbox');
document.body.append(list);
const options: HTMLLIElement[] = items.map((label, index) => {
const li = document.createElement('li');
li.setAttribute('role', 'option');
li.textContent = label;
li.tabIndex = index === 0 ? 0 : -1;
list.append(li);
return li;
});
function focusAt(index: number): void {
const next = (index + options.length) % options.length; // wrap at ends
for (const [i, item] of options.entries()) {
item.tabIndex = i === next ? 0 : -1;
}
options[next].focus();
}
list.addEventListener('keydown', (event) => {
const current = options.indexOf(document.activeElement as HTMLLIElement);
if (event.key === 'ArrowDown') focusAt(current + 1);
else if (event.key === 'ArrowUp') focusAt(current - 1);
else if (event.key === 'Home') focusAt(0);
else if (event.key === 'End') focusAt(options.length - 1);
else return;
event.preventDefault();
});
console.log('tabbable option:', items[options.findIndex((item) => item.tabIndex === 0)]);
focusAt(2);
list.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true }));
console.log('after arrow down, focused:', document.activeElement?.textContent);