最可靠方案是用 IntersectionObserver 触发动画,配合 class 控制、animation-fill-mode: backwards/forwards、避免 height/display 动画及 will-change bug,扩大触发区防漏播。

动画触发区用 IntersectionObserver 最可靠
CSS @keyframes 和 animation 本身不感知滚动或进入视口,必须靠 JS 判断元素是否“可见”才能启动。硬写 scroll 事件监听容易卡顿、误判、兼容性差,IntersectionObserver 是现代标准解法。
它原生支持异步回调、可设阈值(如 threshold: 0.1 表示 10% 进入视口就触发)、自动处理 iframe 和缩放场景:
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('animate-in');
observer.unobserve(entry.target); // 触发后停用,避免重复
}
});
}, { threshold: 0.1 });
document.querySelectorAll('.js-animate').forEach(el => observer.observe(el));
- 务必加
observer.unobserve(),否则同一元素可能多次触发 - 不要在
isIntersecting === true时直接改style.animation,优先用 class 控制,利于 CSS 维护 - IE 不支持,需引入 polyfill 或降级为 scroll 监听
CSS 动画类要配 animation-fill-mode: backwards
如果动画只在进入后播放一次,且希望初始状态是“未动画前”的样式(比如从透明到不透明),不加 animation-fill-mode 会导致元素一开始显示最终帧,闪一下才重播。
正确写法示例:
立即学习“前端免费学习笔记(深入)”;
.animate-in {
opacity: 0;
transform: translateY(20px);
animation: slideUp 0.6s ease-out forwards;
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
-
forwards等价于animation-fill-mode: forwards,让动画停在最后一帧 - 若想回到初始态(比如 hover 触发的循环动画),改用
animation-fill-mode: backwards或省略 - 避免对
height或display做动画——它们无法 GPU 加速,会掉帧
移动端 Safari 的 will-change 要慎用
部分 iOS 版本(尤其是 iOS 15.4–16.3)对 will-change: transform 有渲染 bug:元素可能错位、闪烁,或导致 IntersectionObserver 回调延迟甚至丢失。
实测更稳的替代方案:
- 用
transform: translateZ(0)强制硬件加速,比will-change更轻量 - 只在动画元素上加,不要全局塞到
body或容器上 - 动画结束后主动移除
transform内联样式(如果 JS 控制),避免影响后续布局计算
触发区高度太小会导致动画漏播
当目标元素只有几像素高(比如一个细分割线、border-bottom 模拟的触发线),IntersectionObserver 可能因四舍五入或 subpixel 渲染判定为“未相交”,尤其在缩放或高清屏下。
解决方法不是调低 threshold,而是扩大观测范围:
- 给目标元素加
padding-top: 1px或margin-top: -1px微调布局边界 - 用伪元素撑开观测区:
::before { content: ""; position: absolute; top: -10px; height: 10px; width: 100%; } - 更彻底:观测父容器,再用
getBoundingClientRect()精确判断子元素是否真正进入
这类细节在 PC 上不明显,但在 iPad 或折叠屏设备上极易暴露——别等上线后收用户反馈才排查。










