紀錄工作經驗、相關知識,解決技術相關問題。

CSS, 網站相關

CSS 滾動動畫教學:animation-timeline 的 scroll() 與 view()

CSS 滾動動畫 Scroll-driven Animations 完整解析:animation-timeline 語法與實務範本 特色圖片

💡 文章重點摘要:CSS Scroll-driven Animations 用 animation-timeline 搭配 scroll()、view(),把動畫進度綁定到捲動進度,不需要用 JavaScript 監聽 scroll 事件,就能做出閱讀進度條與捲動淡入效果。本文附兩個可直接套用的範本,以及動畫沒反應、舊瀏覽器相容、橫向捲動的處理方式。

過去要在網頁上做「滾動視差」或「捲動進度條」,通常得監聽 scroll 事件,或引入 GSAP、ScrollMagic 等 JavaScript 函式庫。W3C 的 Scroll-driven Animations 規範讓 CSS 可以直接用捲動進度驅動動畫,目前 Chrome 115、Safari 26、Firefox 159 起都已支援。


1. 原生 animation-timeline:無須 JS 監聽的捲動進度動畫實作

現代 CSS 的核心解法是利用 animation-timeline 屬性,搭配 scroll() 函式,將動畫進度直接綁定到容器的捲動進度上。基本語法如下:

/* 核心標準語法:將動畫綁定至捲動進度 */
.target-element {
  animation: your-animation-name auto linear;
  animation-timeline: scroll(); /* 預設 nearest:最近一個有捲軸的祖先元素 */
}

範本一:頂部閱讀進度條

不需要用 JavaScript 監聽 scrollTop,以下 CSS 就能做出跟著頁面捲動延伸的進度條:

.progress-bar {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 8px;
  background-color: #0070f3;
  transform-origin: left;
  
  /* 1. 綁定自訂動畫 */
  animation: grow-progress auto linear;
  /* 2. 將時間軸綁定到 root 視窗捲動 */
  animation-timeline: scroll(root);
}

@keyframes grow-progress {
  from { transform: scaleX(0); }
  to { transform: scaleX(1); }
}

範本二:元素進入視窗時淡入(Fade-in on scroll)

若要讓動畫跟著「某個區塊在畫面中的位置」推進,應使用 view() 函式:

.card {
  opacity: 0;
  transform: translateY(50px) scale(0.9);
  
  animation: fade-in-up auto linear forwards;
  /* 關鍵:依此元素在可視範圍中的位置推進動畫 */
  animation-timeline: view();
  /* 調整觸發區間:進入視窗 10% 開始,40% 時完成 */
  animation-range: entry 10% entry 40%;
}

@keyframes fade-in-up {
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

2. 頁面切換的轉場動畫:View Transitions API

Scroll-driven Animations 處理的是「捲動時」的動畫;若要做的是頁面或 DOM 切換時的轉場效果,要用另一套 View Transitions API(document.startViewTransition() 搭配 CSS view-transition-name)。它的用法、view-transition-name 必須唯一的限制與效能注意事項,可前往 View Transitions API 效能優化教學 觀看。


3. 常見問題(Q&A)與排錯技巧

Q1:為什麼我的 animation-timeline: scroll() 沒有反應?

解法:依 MDN 文件,先檢查兩件事:

  1. animation-timeline 是否寫在 animation 簡寫之後:animation 簡寫會把 animation-timeline 重設為 auto,所以 animation-timeline 必須寫在 animation 後面(或用更高的權重),才會生效。
  2. 捲動容器在該方向是否真的有捲軸:scroll() 預設找最近一個有捲軸的祖先元素;如果指定方向沒有捲軸,時間軸會失效(inactive)。要綁定整頁捲動時,可直接寫 scroll(root)。

Q2:如何處理舊版瀏覽器不支援的問題?

解法:目前 Chrome 115、Safari 26、Firefox 159 起都已支援 animation-timeline,只有更舊的版本需要處理。可以用 @supports 做漸進式增強,或參考 polyfill 專案 flackr/scroll-timeline:

@supports not (animation-timeline: scroll()) {
  /* 不支援時隱藏進度條,避免顯示一條不會動的色條 */
  .progress-bar { display: none; }
}

Q3:可以實作「橫向捲動」的動畫嗎?

解法:可以,在 scroll() 中指定軸向 x(或依書寫方向的 inline)即可,捲動容器在橫向必須有捲軸:

animation-timeline: scroll(x);
/* 同時指定捲動容器:以元素自己為捲動容器 */
animation-timeline: scroll(x self);

Q4:原生 CSS 動畫真的能完全取代 GSAP 嗎?

解法:基礎的捲動進度、淡入淡出、簡單位移,用原生 CSS 就能完成,不必載入額外函式庫。若需要複雜的「時間軸序列控制(Timeline Sequencing)」或「SVG 路徑動畫」,GSAP 等函式庫提供的工具仍比較完整。


參考資料與延伸閱讀

發佈留言