You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Svelte中将Lottie动画设为背景并在上方叠加文字

问题核心原因

  1. z-index 仅对 position 属性不为默认值static的元素生效,你当前所有元素都使用默认静态定位,所以调整z-index不会产生任何效果
  2. 当前Lottie播放器和文字元素同属普通文档流,默认会按照从上到下的顺序排布,不会出现层叠效果

解决方案

  • 给承载动画和文字的父容器.animation设置相对定位,作为层叠上下文的基准
  • 给lottie-player设置绝对定位,使其脱离普通文档流,占满父容器空间作为背景层
  • 给文字元素设置相对定位,并指定更高的z-index,使其显示在动画层上方
  • 优化项:外部脚本不要放在模板节点内,建议放到svelte:head标签中引入避免重复加载;资源路径的反斜杠替换为正斜杠适配多环境

修改后完整代码

<svelte:head>
  <script src="https://unpkg.com/@lottiefiles/lottie-player@latest/dist/lottie-player.js"></script>
</svelte:head>

<section>
  <div class="animation">
    <lottie-player src="static/animation.json" background="transparent" speed="1" loop autoplay></lottie-player>
    <h1>Title</h1>
    <h2>Text</h2>
  </div>
</section>

<style>
  section {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    flex: 1;
  }

  .animation {
    position: relative;
    width: 1000px;
    height: 1000px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }

  lottie-player {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;
  }

  h1, h2 {
    position: relative;
    z-index: 1;
  }

  h1 {
    width: 100%;
    text-align: center;
  }

  h2 {
    text-align: center;
  }
</style>

内容的提问来源于stack exchange,提问作者J.B.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 11:39:02