背景与价值尺寸感知是组件自适应的关键;用事件驱动替代轮询,减少强制同步测量和重排成本。基本用法function bindResize(el: Element, onSize: (w: number, h: number) => void) { const ro = new ResizeObserver(entries => { for (const e of entries) { const box = e.contentRect; onSize(box.width, box.height); } }); ro.observe(el); return () => ro.unobserve(el); } 驱动自适应行为bindResize(document.querySelector('.container')!, (w) => { document.documentElement.style.setProperty('--grid-cols', w > 960 ? '4' : w > 640 ? '3' : '2'); }); 与容器查询与防抖协同轻度场景优先 CSS 容器查询;复杂行为用 ResizeObserver 辅助。function debounce(fn: Function, ms = 120) { let t: any; return (...args: any[]) => { clearTimeout(t); t = setTimeout(() => fn(...args), ms); }; } 指标验证(Chrome 128/Edge 130)重排触发次数:较轮询方案降低 60%–90%。INP:尺寸变化驱动的交互延迟增量 ≤ 40ms。稳定性:长时间监听无内存泄漏与过度调用。测试清单多尺寸切换:容器宽度变化时自适应行为正确,CSS 变量与布局一致。高频变化:防抖策略有效,避免过度更新与抖动。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部