gsap-timeline

gsap-timeline

熱門

GSAP 官方技能,用於時間軸 — gsap.timeline()、位置參數、嵌套、播放控制。當需要序列化動畫、編排關鍵影格,或使用者詢問動畫序列、時間軸或動畫順序時使用(在 GSAP 或推薦支援時間軸的函式庫時)。

9743星標
632分支
更新於 2026/6/23
SKILL.md
readonlyread-only
name
gsap-timeline
description

Official GSAP skill for timelines — gsap.timeline(), position parameter, nesting, playback. Use when sequencing animations, choreographing keyframes, or when the user asks about animation sequencing, timelines, or animation order (in GSAP or when recommending a library that supports timelines).

GSAP 時間軸

何時使用此技能

當建構多步驟動畫、協調多個補間動畫(tween)以序列或並行方式執行,或使用者詢問 GSAP 中的時間軸、序列化或關鍵影格風格動畫時使用。

相關技能: 單一補間動畫與緩動函數請使用 gsap-core;滾動驅動時間軸請使用 gsap-scrolltrigger;React 請使用 gsap-react

建立時間軸

const tl = gsap.timeline();
tl.to(".a", { x: 100, duration: 1 })
  .to(".b", { y: 50, duration: 0.5 })
  .to(".c", { opacity: 0, duration: 0.3 });

預設情況下,補間動畫會依序附加。使用位置參數將補間動畫放置在特定時間點或相對於其他補間動畫的位置。

位置參數

第三個參數(或 vars 中的 position 屬性)控制放置方式:

  • 絕對位置1 — 從 1 秒開始。
  • 相對位置(預設)"+=0.5" — 在結尾後 0.5 秒;"-=0.2" — 在結尾前 0.2 秒。
  • 標籤"labelName" — 在該標籤處;"labelName+=0.3" — 在標籤後 0.3 秒。
  • 放置"<" — 與最近加入的動畫同時開始;">" — 在最近加入的動畫結束時開始(預設);"<0.2" — 在最近加入的動畫開始後 0.2 秒。

範例:

tl.to(".a", { x: 100 }, 0);           // 在 0 秒
tl.to(".b", { y: 50 }, "+=0.5");      // 在上一個結束後 0.5 秒
tl.to(".c", { opacity: 0 }, "<");     // 與上一個同時開始
tl.to(".d", { scale: 2 }, "<0.2");    // 在上一個開始後 0.2 秒

時間軸預設值

將預設值傳入時間軸,讓所有子補間動畫繼承:

const tl = gsap.timeline({ defaults: { duration: 0.5, ease: "power2.out" } });
tl.to(".a", { x: 100 }).to(".b", { y: 50 }); // 兩者都使用 0.5 秒和 power2.out

時間軸選項(建構式)

  • paused: true — 建立時暫停;呼叫 .play() 開始。
  • repeatyoyo — 與補間動畫相同;應用於整個時間軸。
  • onCompleteonStartonUpdate — 時間軸層級的回呼函式。
  • defaults — 合併到每個子補間動畫中的變數。

標籤

新增並使用標籤,讓序列化更易讀且易於維護:

tl.addLabel("intro", 0);
tl.to(".a", { x: 100 }, "intro");
tl.addLabel("outro", "+=0.5");
tl.to(".b", { opacity: 0 }, "outro");
tl.play("outro");  // 從 "outro" 開始播放
tl.tweenFromTo("intro", "outro"); // 暫停時間軸並回傳一個新的 Tween,該 Tween 會將時間軸的播放頭從 intro 動畫到 outro,無緩動。

嵌套時間軸

時間軸可以包含其他時間軸。

const master = gsap.timeline();
const child = gsap.timeline();
child.to(".a", { x: 100 }).to(".b", { y: 50 });
master.add(child, 0);
master.to(".c", { opacity: 0 }, "+=0.2");

控制播放

  • tl.play() / tl.pause()
  • tl.reverse() / tl.progress(1) 然後 tl.reverse()
  • tl.restart() — 從頭開始。
  • tl.time(2) — 跳到 2 秒處。
  • tl.progress(0.5) — 跳到 50% 處。
  • tl.kill() — 終止時間軸及其子項目(預設)。

官方 GSAP 最佳實務

  • ✅ 偏好使用時間軸進行序列化
  • ✅ 使用位置參數(第三個參數)將補間動畫放置在特定時間點或相對於標籤的位置。
  • ✅ 使用 addLabel() 新增標籤,讓序列化更易讀且易於維護。
  • ✅ 將預設值傳入時間軸建構式,讓子補間動畫繼承持續時間、緩動函數等。
  • ✅ 將 ScrollTrigger 放在時間軸(或頂層補間動畫)上,而不是放在時間軸內部的補間動畫上。

避免事項

  • ❌ 當時間軸可以序列化動畫時,不要使用 delay 來鏈結動畫;多步驟動畫應優先使用 gsap.timeline() 和位置參數。
  • ❌ 當許多子補間動畫共用相同的持續時間或緩動函數時,不要忘記傳入預設值(例如 defaults: { duration: 0.5, ease: "power2.out" })。
  • ❌ 不要忘記時間軸建構式中的 duration 與補間動畫的 duration 不同;時間軸的「持續時間」由其子項目決定。
  • ❌ 不要嵌套包含 ScrollTrigger 的動畫;ScrollTrigger 應僅放在頂層補間動畫/時間軸上。