iter(g106): 滚动监听改为卸载自清理

This commit is contained in:
HIsheR
2026-10-26 13:58:22 +08:00
parent 7d57f261df
commit c66bcf35da
6 changed files with 31 additions and 11 deletions
+15
View File
@@ -0,0 +1,15 @@
/*** 滚动 / 视口监听:根节点被移出文档后自动摘净监听,避免单页应用里反复挂载累积监听 ***/
export function watchViewport(root: HTMLElement, host: HTMLElement | Window, handler: () => void): void {
// —— 状态集中声明 ——
const run = (): void => {
if (!root.isConnected) { // 已卸载:一次性摘掉 scroll 与 resize,后续不再进 handler
host.removeEventListener('scroll', run);
window.removeEventListener('resize', run);
return;
}
handler();
};
host.addEventListener('scroll', run, { passive: true }); // 被动监听:不阻塞滚动
window.addEventListener('resize', run); // 视口变化会改判定线与可滚距离
handler(); // 首帧同步一次:刷新时停在页面中段也能得到正确状态
}