如何实现上一段打字机动画完成后再播放下一段动画?
实现逐行触发的打字机动画
要让第二行的打字动画在第一行完成后启动,核心是利用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
相关产品推荐
相关产品推荐

