滚动动画技能 是做什么的?
工作流程
- 确认动画风格、时长,以及动画是一次性播放还是重复播放。
- 提供关键帧 + JS 观察器代码片段,以及精确的 Tailwind 类。
- 仅进行有针对性的调整(阈值、根边距、时长、延迟、变换/模糊值)。
使用检查清单
- 将 JS 代码片段插入到关键帧之后的
<head> 中。
- 为元素添加动画类和
animate-on-scroll 类。
- 确保关键帧名称与 Tailwind 动画引用匹配。
IntersectionObserver 触发器
<script>
(function () {
const style = document.createElement("style");
style.textContent = `
/* 默认:暂停 */
.animate-on-scroll { animation-play-state: paused !important; }
/* 由 JS 激活 */
.animate-on-scroll.animate { animation-play-state: running !important; }
`;
document.head.appendChild(style);
const once = true;
if (!window.__inViewIO) {
window.__inViewIO = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
entry.target.classList.add("animate");
if (once) window.__inViewIO.unobserve(entry.target);
}
});
}, { threshold: 0.2, rootMargin: "0px 0px -10% 0px" });
}
window.initInViewAnimations = function (selector = ".animate-on-scroll") {
document.querySelectorAll(selector).forEach((el) => {
window.__inViewIO.observe(el);
});
};
document.addEventListener("DOMContentLoaded", () => initInViewAnimations());
})();
</script>
关键帧
<style>
@keyframes animationIn {
0% {
opacity: 0;
transform: translateY(30px);
filter: blur(8px);
}
100% {
opacity: 1;
transform: translateY(0);
filter: blur(0px);
}
}
</style>
Tailwind 示例
<div class="animate-on-scroll [animation:animationIn_0.8s_ease-out_0.1s_both]">
...
</div>
自定义调节旋钮
- 触发时机:调整
threshold 和 rootMargin 以实现更早或更晚的显示。
- 重复播放:将
once 设置为 false 以允许重新进入视口时重复播放。
- 动效:在关键帧中调整
translateY 和 blur。
- 时长:在 Tailwind 动画值中更改持续时间和延迟。
常见陷阱
- 忘记在 JS 代码片段之前包含关键帧。
- 使用与 Tailwind 动画不同名称的关键帧。
- 由于元素在观察器初始化时已在视口中,导致动画不运行。
缺少规格时需要询问的问题
- 动画是一次性播放,还是每次元素重新进入视口时播放?
- 动画应该在进入视口前多远开始?
- 您想要哪种动效风格(淡入、滑动、模糊、缩放)?