如何在Svelte中将Lottie动画设为背景并在上方叠加文字
问题核心原因
z-index仅对position属性不为默认值static的元素生效,你当前所有元素都使用默认静态定位,所以调整z-index不会产生任何效果- 当前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.
相关产品推荐
相关产品推荐

