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

如何实现上一段打字机动画完成后再播放下一段动画?

实现逐行触发的打字机动画

要让第二行的打字动画在第一行完成后启动,核心是利用animation-delay属性,将第二行的动画延迟设置为第一行打字动画的总时长。同时要为不同段落单独配置动画参数(比如steps数量对应字符数、动画时长匹配字号),确保效果协调自然。

关键调整点:

  • 第一行打字动画时长为3s,因此第二行的animation-delay设为3s,刚好等第一行完成后开始。
  • 第二行字符数为16("Let's get started!"),所以设置steps(16),同时根据3rem的字号调整动画时长为4s,保证打字速度与字号匹配。
  • 保留forwards关键字,让动画结束后元素保持最终宽度,避免回弹。
  • 给第二行初始设置width: 0,防止页面加载时文本提前显示。

完整代码:

CSS

.typewriter{
  display: flex;
  justify-content: center;
}

.typewriter .p1, .p2{
  font-family: monospace;
  overflow: hidden;
  white-space: nowrap;
  border-right: 3px solid;
}

.typewriter .p1{
  font-size: 1.5rem;
  animation: typing 3s steps(22) forwards, blink 1s step-end infinite;
}

.typewriter .p2{
  font-size: 3rem;
  width: 0;
  /* 延迟时间等于第一行打字动画的时长 */
  animation: typing 4s steps(16) forwards, blink 1s step-end infinite;
  animation-delay: 3s;
}

@keyframes typing{
  from{
    width: 0;
  }
  
  to{
    width: 100%;
  }
}

@keyframes blink{
  50%{
    border-color: transparent;
  }
}

HTML

<div class="typewriter">
  <div>
    <p class="p1">Hello, Welcome to CodePen!</p>
    <p class="p2">Let's get started!</p>
  </div>
</div>

额外说明:

如果需要第一行光标闪烁一段时间后再启动第二行,可以在延迟时间上增加额外秒数,比如animation-delay: 3.5s,灵活调整衔接节奏。

内容的提问来源于stack exchange,提问作者Nayan Anand

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 14:22:03