滾動動畫技巧
工作流程
- 確認動畫風格、時機,以及動畫應執行一次或重複。
- 提供關鍵影格 + JS 觀察器程式碼片段,以及確切的 Tailwind 類別來套用。
- 僅提供針對性的調整(threshold、rootMargin、duration、delay、transform/blur 值)。
使用檢查清單
- 將 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 動畫中不同的關鍵影格名稱。
- 動畫無法執行,因為元素在觀察器初始化前已在視窗內。
規格遺漏時應提出的問題
- 動畫應執行一次還是每次元素重新進入時執行?
- 應在進入視窗多遠前開始觸發?
- 想要哪種動態風格(淡入、滑入、模糊、縮放)?