实现说明
各个操作都建立在顶层绑定之上: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');
});