← 中文资源

简体中文版本

delegatesFocus 把宿主聚焦路由进内部

attachShadow 开 delegatesFocus 后,聚焦宿主会把焦点交给 shadow 内第一个可聚焦节点,无需给宿主加 tabindex;外部监听 focusin 时目标被重定向回宿主。

阅读英文原文

实现说明

各个操作都建立在顶层绑定之上:host、root。

使用要点

  • document 只存在于浏览器——Node 运行时没有现成的垫片。
  • 跑完文件,输出里会留下标记——host default tabindex:、focusout seen on host。

常见问题

「delegatesFocus 把宿主聚焦路由进内部」能在裸 Node.js 里跑吗?

不能——document 的家在浏览器里,Node 进程提供不了。执行时请用页面(或 DevTools 控制台)。

核心语句

host.addEventListener('focusout', () => {
  console.log('focusout seen on host');
});
host.addEventListener('focusin', () => {
  console.log('focusin seen on host (retargeted from inside shadow)');
});

代码示例

const host = document.querySelector('profile-card') as HTMLElement;
const root = host.attachShadow({ mode: 'open', delegatesFocus: true });

root.innerHTML = `
  <button>Follow</button>
  <input placeholder="search" />
`;

// delegatesFocus: focusing the host pushes focus to the first focusable
// node inside the shadow root instead of needing a tabindex on the host.
host.focus();
console.log('host default tabindex:', host.tabIndex);

host.addEventListener('focusin', () => {
  console.log('focusin seen on host (retargeted from inside shadow)');
});

host.addEventListener('focusout', () => {
  console.log('focusout seen on host');
});