SuperAPI AI 工具集

css-transition-stuck-spa-navigation

前端与建站

查看项目

更新于 10-15 22:15

技能介绍

用途:修复单页应用(SPA)在页面切换后,滚动显现元素(.reveal 等)的 CSS 过渡卡在初始状态的问题——即使 .visible 类已存在,元素仍保持 opacity: 0,内联样式(含 !important)也无效,但首次加载正常。

触发条件:页面区块用 display: none/block 切换;.reveal 定义 transition: opacity 0.7s, transform 0.7s;导航函数先移除再重新添加 .visible(含经 IntersectionObserver 的情况);症状为 getComputedStyle(el).opacity 返回 "0",双重 requestAnimationFrame 也无法修复。

根因:浏览器把同一绘制周期内的“移除类—重新添加类”批处理为一次样式重算,过渡起止状态同时算出,不触发动画,元素停留在基础值 opacity: 0。

做法:在移除 .visible 后将 el.style.transition 设为 'none',用 void container.offsetHeight 强制同步重排,再恢复 transition 为 '',再次强制重排,最后添加 .visible 并调用 IntersectionObserver 与 forceCheckViewport(),让视口内元素立即显现。

验证:切换页面后顶部元素应平滑淡入(opacity 0→1),过渡完成后 getComputedStyle(el).opacity 返回 "1";视口外元素保持 opacity: 0 直到滚入。

限制:该问题只在“移除后再添加同一类”时出现;prefers-reduced-motion 应直接设 opacity: 1、transform: none 以绕过整套机制;其他重排触发属性(offsetWidth、getComputedStyle(el).opacity)也可用。