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

如何在CSS打字效果完成后停止动画?

打字完成后停止动画的实现方法

要让文字完成打字后停止动画(包括光标闪烁),可以通过以下两种方案实现:

纯CSS方案

核心思路是让光标闪烁动画的时长与打字动画一致,结束后保持光标隐藏的状态:

修改原CSS中的animation属性,将光标动画的infinite(无限循环)替换为forwards,并设置时长与打字动画相同:

.col-twelve h5 {
  overflow: hidden; /* 确保内容在动画完成前不显示 */
  border-right: 0.15em solid orange; /* 打字机光标 */
  white-space: nowrap; /* 保持内容单行显示 */
  margin: 0 auto; /* 实现打字时的滚动效果 */
  letter-spacing: 0.15em; /* 按需调整字符间距 */
  animation: typing 3.5s steps(50, end) forwards,
    blink-caret 3.5s step-end forwards; /* 修改光标动画为与打字同时长,结束后保持状态 */
}

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

@keyframes blink-caret {
  from,
  to {
    border-color: transparent;
  }
  50% {
    border-color: rgb(255, 255, 255);
  }
}

这样,当3.5秒的打字动画完成时,光标动画也同步结束,最终光标会停在透明状态,动画完全停止。

JavaScript方案(更灵活)

通过监听动画结束事件,在打字完成后手动移除动画和光标:

<div class="col-twelve">
   <h5>print("Hello, World!")</h5>
</div>

<script>
const typewriterElement = document.querySelector('.col-twelve h5');
typewriterElement.addEventListener('animationend', function(e) {
  // 仅在打字动画结束时执行
  if (e.animationName === 'typing') {
    this.style.animation = 'none'; // 移除所有动画
    this.style.borderRight = 'none'; // 隐藏光标
  }
});
</script>

<style>
.col-twelve h5 {
  overflow: hidden;
  border-right: 0.15em solid orange;
  white-space: nowrap;
  margin: 0 auto;
  letter-spacing: 0.15em;
  animation: typing 3.5s steps(50, end) forwards,
    blink-caret 0.75s step-end infinite;
}

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

@keyframes blink-caret {
  from,
  to {
    border-color: transparent;
  }
  50% {
    border-color: rgb(255, 255, 255);
  }
}
</style>

这种方案适合需要在动画结束后执行更多自定义逻辑的场景。

内容的提问来源于stack exchange,提问作者jospeh hyde

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:20:27