Timeline 时间线
把多个 tween 编成一段可 play / reverse / seek / timeScale 的影片。
复杂入场、菜单开合、滚动 scrub 都应该上时间线,而不是一堆 delay。
位置参数(最重要)
.to(target, vars, position) 的第三个参数决定「插在时间轴的哪里」:
| 写法 | 含义 |
|---|---|
| 省略 | 接在当前轴的末尾(顺序播放) |
0 / 1.2 | 绝对时间(秒) |
"+=0.5" | 相对末尾再晚 0.5s |
"-=0.2" | 与上一段重叠 0.2s |
"<" | 与上一段的起点对齐(同时开始) |
">" | 与上一段的终点对齐 |
"<+0.2" | 上一段开始后再 0.2s |
"intro" | 跳到名为 intro 的标签 |
"intro+=0.3" | 标签后再 0.3s |
默认串联
A
B
const tl = gsap.timeline();
tl.to("#a", { x: 400, duration: 0.8 })
.to("#b", { x: 400, duration: 0.8 })
.to("#a", { rotation: 360, duration: 0.6 });
标签 + 同时启动
C
D
const tl = gsap.timeline();
tl.add("start")
.to("#c", { x: 400, duration: 1.6 }, "start")
.to("#d", { x: 400, duration: 0.9 }, "start+=0.35");
常用实例方法
| 方法 | 说明 |
|---|---|
play() / pause() / reverse() / restart() | 播放控制 |
seek(time | label) | 跳转,不播动画直接切状态 |
progress(0~1) | 按百分比 |
timeScale(2) | 整段加速;0.5 慢放 |
add(label) / add(tween) | 加标签或嵌套别的 tween/tl |
call(fn) | 在轴上某时刻跑函数(切 class、播声音) |
set(target, vars) | 轴上的瞬时 set |
kill() | 销毁;SPA 卸载组件时必做 |
keyframes:一个 tween 里写多段
不想建时间线时,可用 keyframes 数组。百分比或 duration 都可以。复杂编排仍建议 Timeline。
KF
gsap.to("#kfBox", {
keyframes: [
{ x: 180, duration: 0.4 },
{ y: 40, rotation: 90, duration: 0.4 },
{ x: 360, y: 0, rotation: 0, duration: 0.5 }
],
ease: "power2.inOut"
});
默认
defaults: { ease, duration } 可写在 gsap.timeline({ defaults: { duration: 0.6, ease: "power2.out" } }),
子 tween 不用重复写。