实现说明
顶层就这几处状态:rows。
使用要点
- 用到了
document,需要在浏览器环境运行,Node 里直接跑会缺 API。 - 守卫
event.key !== 'ArrowDown' && event.key !== 'ArrowUp'成立时借助提前的return直接离开。 - 跑完文件,输出里会留下标记——
focused row:。
常见问题
「focus 的 preventScroll 保持滚动位置」能在裸 Node.js 里跑吗?
不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。
核心语句
const rows = Array.from(document.querySelectorAll<HTMLElement>('.cmd-row'));
代码示例
// focus() scrolls the newly focused control into view by default, which
// yanks a two-pane layout when the list lives in a side pane. The
// preventScroll option moves focus without touching scroll positions.
const rows = Array.from(document.querySelectorAll<HTMLElement>('.cmd-row'));
document.addEventListener('keydown', (event: KeyboardEvent) => {
if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
event.preventDefault();
const index = rows.indexOf(document.activeElement as HTMLElement);
const step = event.key === 'ArrowDown' ? 1 : -1;
const next = rows[(index + step + rows.length) % rows.length];
if (!next) return;
next.focus({ preventScroll: true });
console.log('focused row:', next.dataset['cmd']);
});