往返与重复

Yoyo & Repeat

Yoyo & Repeat 循环动画 往返动画 重复播放 Loop Ping-pong

用 repeat 控制动画额外重复的次数,-1 表示无限循环;再配合 yoyo 让每次重复时正反交替播放,形成来回往返。

又称:循环动画 · 往返动画 · 重复播放 · Loop · Ping-pong

  • GSAP
  • CSS
  • Claude / Cursor
repeat: 0
×0
repeat: 2
×0
repeat: -1, yoyo: true
×0
repeat / yoyo / repeatDelay

Prompt 片段

  • Claude / Cursor
    用 GSAP 做一个呼吸灯效果:圆点 scale 从 1 到 1.15,duration 1.2,ease sine.inOut,repeat: -1,yoyo: true。
  • Claude / Cursor
    做一个对比演示:三个方块分别使用 repeat: 0、repeat: 2、repeat: -1 加 yoyo: true,repeatDelay 0.3,在 onRepeat 回调里显示已重复的次数。
  • Claude / CursorrepeatRefresh 会让每次重复重新计算起止值
    循环动画每一轮都用 gsap.utils.random 取新的随机位置,开启 repeatRefresh: true,并在元素离开视口时暂停。

是什么

往返与重复是 GSAP 补间和时间轴共有的两个播放参数。repeat 表示在第一次播放之后再额外重复几次:repeat: 2 实际会播放 3 遍,repeat: -1 为无限循环。yoyo: true 让奇数次重复倒着播放,于是动画从 A 到 B、再从 B 回到 A,像溜溜球一样往返。yoyo 只有在 repeat 不为 0 时才有意义。

上方演示有三行:repeat: 0 的方块只走一次就停下;repeat: 2 的方块每次都从左侧重新出发,共走 3 遍,右侧计数到 ×2;最后一行 repeat: -1, yoyo: true 来回往返、永不停止,计数持续增加。每次重复之间都有 repeatDelay: 0.3 的停顿。

核心参数

参数 含义
repeat 额外重复次数,默认 0;-1 为无限
yoyo 重复时正反交替,默认 false
repeatDelay 每次重复之间的间隔(秒)
repeatRefresh 每次重复时重新计算起止值,适合随机值或函数值
yoyoEase 为回程单独指定缓动
onRepeat 每次开始重复时触发的回调

代码示例

import { gsap } from 'gsap';

const count = document.querySelector('.count');
let n = 0;

gsap.to('.dot', {
  x: 300,
  duration: 1.1,
  ease: 'power2.inOut',
  repeat: -1, // 0 只播一次;2 共播 3 遍;-1 无限循环
  yoyo: true, // 奇数次重复倒着播
  repeatDelay: 0.3,
  onRepeat: () => {
    n += 1;
    count.textContent = `×${n}`;
  },
});

什么时候用

  • 加载指示、呼吸灯、悬浮提示等需要持续吸引注意的循环动效。
  • 演示、引导中反复展示一个动作。
  • 背景装饰的缓慢漂浮,配合 sine.inOutyoyo 显得自然。

常见误区

  • 以为 repeat: 2 播放 2 遍:实际是 3 遍,第一次不算重复。
  • 只写 yoyo: true 不写 repeat:没有重复就没有回程,yoyo 不会生效。
  • 在时间轴中放无限循环的子补间:时间轴时长变成无限,后续补间无法到达。循环动画应独立创建,或把 repeat 设在时间轴上。
  • 页面上长期运行大量无限循环:元素不可见时应暂停,节省性能。
esc