← 中文资源

简体中文版本

focus 的 preventScroll 保持滚动位置

键盘导航时用 focus({ preventScroll: true }):焦点在面板之间移动但不抢占视口滚动,用户阅读位置保持原处。

阅读英文原文

实现说明

顶层就这几处状态: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']);
});