关于 animation-on-scroll
面向前端开发者的滚动动画技能,指导使用 IntersectionObserver 在元素进入视口时触发 Tailwind 动画。提供触发时机、重复播放、位移和时长等调整建议。
主要功能
- 01IntersectionObserver 触发动画
- 02Tailwind 动画类用法
- 03调整视口触发范围
- 04配置重复播放与时序
适用场景
- 01让内容进入视口时依次显示
- 02调整动画触发的提前量
- 03设置动画只播放一次或重复播放
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ mengto/ skills --skill animation-on-scroll安装后在 Claude Code 中输入/animation-on-scroll确认已加载。
附带文件demo/index.htmldemo/PROMPT.md
详细介绍
滚动时触发动画技能
工作流
- 确认动画风格、时长,以及动画应只运行一次还是重复运行。
- 提供关键帧、JS 观察器代码片段,以及要应用的确切 Tailwind 类。
- 仅提供针对性的调整(阈值、rootMargin、时长、延迟、变换/模糊值)。
使用检查清单
- 将 JS 代码片段插入
<head>中,并放在关键帧之后。 - 为元素添加动画类和
animate-on-scroll。 - 确保关键帧名称与 Tailwind 动画引用一致。
IntersectionObserver 触发器
<script>
/*
Sequence animation on scroll when visible. Requires Animation Keyframe. Usage:
1) Insert this code in the <head> along with the Animation Keyframe code.
2) Add to Tailwind Classes: [animation:animationIn_0.8s_ease-out_0.1s_both] animate-on-scroll
*/
(function () {
// Inject CSS for paused/running states
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); // observing twice is a no-op
});
};
document.addEventListener("DOMContentLoaded", () => initInViewAnimations());
})();
</script>
关键帧
<style>
/*
Sequence animation intro. Usage:
1) Insert this code in the <head>
2) Add to Tailwind Classes: [animation:animationIn_0.8s_ease-out_0.1s_both]
*/
@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 动画中不同的关键帧名称。
- 由于观察器初始化前元素已处于视口中,导致动画未运行。
规格缺失时要询问的问题
- 动画应只运行一次,还是每次元素重新进入时都运行?
- 动画应在元素进入视口前多远开始?
- 你想要哪种动效风格(淡入、滑动、模糊、缩放)?
评论
支持 Markdown