| name | animation-on-scroll |
| description | 用 IntersectionObserver 创建滚动触发动画,配 Tailwind 友好的动画类与 keyframes。当被要求做滚动显现、animate-on-scroll,或在元素进入视口时对其动画进行排序时使用。 |
Animation On Scroll 技能
工作流程
- 确认动画风格、时机,以及动画应运行一次还是重复。
- 提供 keyframes + JS observer 片段,以及要应用的确切 Tailwind 类。
- 只提供聚焦的微调(threshold、rootMargin、duration、delay、transform/blur 值)。
使用检查清单
- 把 JS 片段插入
<head>,放在 keyframes 之后。
- 给元素添加动画类与
animate-on-scroll。
- 确保你的 keyframes 名称与 Tailwind 动画引用匹配。
IntersectionObserver 触发器
<script>
(function () {
const style = document.createElement("style");
style.textContent = `
/* Default: paused */
.animate-on-scroll { animation-play-state: paused !important; }
/* Activated by 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>
Keyframes
<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 以允许重新进入时重播。
- 动效:微调 keyframes 里的
translateY 与 blur。
- 时机:改 Tailwind 动画值里的 duration 与 delay。
常见坑
- 忘记在 JS 片段之前放入 keyframes。
- 用了与 Tailwind 动画不同的 keyframe 名称。
- 因元素在 observer 初始化前已在视口内,导致动画不运行。
规格缺失时该问的问题
- 动画应运行一次,还是元素每次重新进入都运行?
- 应在进入视口前多远开始?
- 你想要什么动效风格(淡入、滑动、模糊、缩放)?