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

网页添加Typewriter动画遇问题:光标异常及动画触发顺序咨询

打字机动画问题修复与实现

一、光标偏移错误修复

问题原因

光标偏移至容器最右侧,是因为h1作为块级元素默认宽度100%,动画中width:100%会让光标停在容器末端,而非文字结尾。

修复步骤

  1. 给.typeWriter1和.typeWriter2添加display: inline-block,使元素宽度由内容决定;
  2. 移除margin: 0 auto,依赖父容器text-align: center实现居中;
  3. 根据文字实际字符数调整typing动画的steps参数,减少冗余动画帧。

修改后的核心CSS:

.typeWriter .typeWriter1,
.typeWriter .typeWriter2 {
  overflow: hidden;
  border-right: .15em solid orange;
  white-space: nowrap;
  display: inline-block;
  letter-spacing: .15em;
}

.typeWriter1 {
  animation: typing 3.5s steps(9, end), blink-caret .75s step-end infinite;
  /* "I am Anay," 共9个字符,steps匹配字符数更精准 */
}

二、顺序触发打字动画实现

方案1:纯CSS延迟启动

利用animation-delay将第二个动画的启动时间设为第一个动画的时长(3.5s),同时默认隐藏第二个元素,动画结束后保持展开状态:

.typeWriter2 {
  width: 0;
  border-color: transparent;
  animation: typing 3.5s steps(12, end) 3.5s forwards, blink-caret .75s step-end infinite 3.5s;
  /* forwards:动画结束后保留最后一帧宽度 */
}

说明:steps(12, end)对应"A programmer"的字符总数(含空格),延迟时间与第一个动画时长一致,确保顺序执行。

方案2:JavaScript监听动画结束

若需动态控制动画(比如时长可变),通过animationend事件触发第二个动画:

<script>
const el1 = document.querySelector('.typeWriter1');
const el2 = document.querySelector('.typeWriter2');

// 初始隐藏第二个元素
el2.style.width = '0';
el2.style.borderRight = 'none';

el1.addEventListener('animationend', (e) => {
  if (e.animationName === 'typing') {
    el2.style.animation = 'typing 3.5s steps(12, end) forwards, blink-caret .75s step-end infinite';
    el2.style.borderRight = '.15em solid orange';
  }
});
</script>

卡顿问题优化

之前使用display: inline-block出现卡顿,多因steps参数过大或初始状态未设置宽度。修复时:

  • 按文字实际字符数设置steps;
  • 未启动动画的元素设width:0,减少重绘开销。

完整代码示例

#introduction {
  font-size: 175%;
  color: #d3d3d3;
  text-align: center;
  font-family: "Solitreo", sans-serif;
}

.typeWriter .typeWriter1,
.typeWriter .typeWriter2 {
  overflow: hidden;
  border-right: .15em solid orange;
  white-space: nowrap;
  display: inline-block;
  letter-spacing: .15em;
  margin: 0.5em 0;
}

.typeWriter1 {
  animation: typing 3.5s steps(9, end), blink-caret .75s step-end infinite;
}

.typeWriter2 {
  width: 0;
  border-color: transparent;
  animation: typing 3.5s steps(12, end) 3.5s forwards, blink-caret .75s step-end infinite 3.5s;
}

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

@keyframes blink-caret {
  from, to { border-color: transparent }
  50% { border-color: orange }
}
<div id="introduction">
  <div class="typeWriter">
    <h1 class="typeWriter1">I am Anay,</h1>
    <br>
    <h1 class="typeWriter2">A programmer</h1>
  </div>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:40:26