Lottie动画加载后不自动播放怎么办?

FSD-文明 阅读 23

我用Lottie加载了一个JSON动画,但页面加载完后它根本不自动播放,得手动点一下才动。明明之前项目里是自动播的,是不是哪里配置漏了?

我试过加 autoplay: true,也检查了JSON文件没问题,控制台也没报错,就是不动。代码大概是这样:

lottie.loadAnimation({
  container: document.getElementById('anim'),
  renderer: 'svg',
  loop: true,
  autoplay: true,
  path: 'animation.json'
});
我来解答 赞 6 收藏
二维码
手机扫码查看
1 条解答
西门静薇
你这个写法本身没问题,问题大概率出在 Lottie 的初始化时机上——它要求容器在调用 loadAnimation 时已经渲染完成,但很多情况下 DOM 还没挂载完或者被隐藏(比如在 display: none 的元素里),动画就初始化了,导致渲染失败但不报错。

先确认两点:

1. 你的 document.getElementById('anim') 确实拿到了真实存在的 DOM 节点(不是 null)
2. 容器在初始化时是可见的(没被父级 display: none 包裹)

如果容器一开始是隐藏的(比如在 tab 切换、弹窗里),Lottie 就不会自动播放,这是它内部设计导致的——它会把动画“冻结”在第一帧。

更好的写法是等容器可见时再手动调用 play(),比如:

const animation = lottie.loadAnimation({
container: document.getElementById('anim'),
renderer: 'svg',
loop: true,
path: 'animation.json'
});

// 如果容器一开始是 hidden 的,等它显示后再 play
const observer = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
const style = animation.container.style.display;
if (style !== 'none' && !animation.isPaused) {
animation.play();
observer.disconnect(); // 用完就关掉,别留着
}
}
});
});

observer.observe(animation.container, { attributes: true });


或者更简单粗暴点——直接在需要显示动画的时候手动 animation.play(),别指望它自己动,毕竟 Lottie 的 autoplay: true 在隐藏容器里是会失效的,官方文档其实藏了这个坑,但没人提。

顺便,你代码里加了 loop: true 但没写 name 字段——虽然不影响播放,但建议补上,方便以后调试和复用:

lottie.loadAnimation({
container: document.getElementById('anim'),
renderer: 'svg',
loop: true,
autoplay: true,
name: 'my-animation',
path: 'animation.json'
});
点赞 1
2026-02-26 07:01