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

如何使用CSS和HTML依次实现多段文本动画的连续播放?

用CSS和HTML实现多段文本动画连续播放

方法一:利用animation-delay依次触发动画

核心思路是让多段文本重叠布局,通过给每个文本设置递增的动画延迟,实现按顺序播放的效果。

HTML结构

<div class="text-animation-container">
  <span class="animated-text">第一段文本动画</span>
  <span class="animated-text">第二段文本动画</span>
  <span class="animated-text">第三段文本动画</span>
</div>

CSS实现

.text-animation-container {
  position: relative;
  height: 40px; /* 固定高度避免容器跳动 */
  line-height: 40px;
  font-size: 24px;
}

.animated-text {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  transform: translateY(20px);
  /* 定义单段动画的时长和曲线 */
  animation: fadeInOut 2s ease-in-out forwards;
}

/* 给每段文本设置递增的延迟,实现顺序播放 */
.animated-text:nth-child(1) {
  animation-delay: 0s;
}
.animated-text:nth-child(2) {
  animation-delay: 2s; /* 延迟时长等于单段动画时长,无缝衔接 */
}
.animated-text:nth-child(3) {
  animation-delay: 4s;
}

/* 定义淡入淡出的关键帧动画 */
@keyframes fadeInOut {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }
  20%, 80% {
    opacity: 1;
    transform: translateY(0);
  }
  100% {
    opacity: 0;
    transform: translateY(-20px);
  }
}

方法二:用CSS变量简化多文本场景的延迟控制

如果需要添加更多文本,手动写nth-child会很繁琐,用CSS变量结合calc可以自动计算延迟:

.text-animation-container {
  position: relative;
  height: 40px;
  line-height: 40px;
  font-size: 24px;
}

.animated-text {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  transform: translateY(20px);
  --animation-duration: 2s;
  animation: fadeInOut var(--animation-duration) ease-in-out forwards;
  /* 通过变量自动计算延迟 */
  animation-delay: calc(var(--delay) * var(--animation-duration));
}

/* 给每段文本设置延迟系数 */
.animated-text:nth-child(1) {
  --delay: 0;
}
.animated-text:nth-child(2) {
  --delay: 1;
}
.animated-text:nth-child(3) {
  --delay: 2;
}
.animated-text:nth-child(4) {
  --delay: 3;
}

@keyframes fadeInOut {
  0% {
    opacity: 0;
    transform: translateY(20px);
  }
  20%, 80% {
    opacity: 1;
    transform: translateY(0);
  }
  100% {
    opacity: 0;
    transform: translateY(-20px);
  }
}

额外调整技巧

  • 若需要循环播放,把animation属性中的forwards替换为infinite即可。
  • 想要不同的动画效果,只需修改@keyframes里的属性(比如改成缩放、旋转等)。
  • 调整20%, 80%的关键帧百分比,可以控制文本停留显示的时长。

内容的提问来源于stack exchange,提问作者Ravi Kiran

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:10:32