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

实现含多行文本及子元素的HTML元素打字动画需求

多行文本及嵌套子元素的打字动画实现方案

问题背景

需要为包含超长多行文本、嵌套子元素的HTML元素实现逐字符(支持自动换行)展示的打字动画,且子元素内的文本也要同步应用该动画。但原基于容器宽度变化的动画方案(移除white-space: nowrap;和overflow: hidden;后)完全失效,无法满足需求。

解决方案

原方案仅适用于单行长文本,针对多行+子元素场景,我们采用JavaScript递归处理文本节点+CSS逐元素动画的思路:

  1. 递归遍历目标元素及其所有子元素,将文本拆分为单个字符并包裹在<span>标签中;
  2. 为每个字符span设置渐入动画,通过延迟控制显示顺序模拟打字效果;
  3. 保留光标闪烁动画,跟随文本展示进度。

完整代码示例

<!DOCTYPE html>
<html>
<head>
<style>
.type-writer {
  position: relative;
  letter-spacing: .15em;
  max-width: 800px; /* 限制宽度触发自动换行 */
  line-height: 1.6;
}

/* 单个字符的打字动画 */
.type-writer .char {
  opacity: 0;
  animation: typeChar 0.1s forwards;
}

@keyframes typeChar {
  to { opacity: 1; }
}

/* 打字光标动画 */
.type-writer::after {
  content: "";
  position: absolute;
  right: -5px;
  top: 0;
  width: .15em;
  height: 100%;
  background-color: orange;
  animation: blinkCaret .5s step-end infinite;
}

@keyframes blinkCaret {
  from, to { background-color: transparent; }
  50% { background-color: orange; }
}

/* 避免子元素样式干扰 */
.type-writer * {
  margin: 0;
  padding: 0;
}
</style>
</head>
<body>
<div class="type-writer">
  <h1>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</h1>
  <p>这是一段嵌套子元素文本,<a href="#">链接内的文字也会同步打字</a>,测试子元素的动画效果。</p>
</div>

<script>
function applyTypewriterEffect(element) {
  const childNodes = Array.from(element.childNodes);
  
  childNodes.forEach(node => {
    // 处理非空文本节点
    if (node.nodeType === Node.TEXT_NODE && node.textContent.trim() !== "") {
      const chars = node.textContent.split("");
      const fragment = document.createDocumentFragment();
      
      chars.forEach(char => {
        const span = document.createElement("span");
        span.className = "char";
        span.textContent = char;
        fragment.appendChild(span);
      });
      
      node.replaceWith(fragment);
    } 
    // 递归处理子元素
    else if (node.nodeType === Node.ELEMENT_NODE) {
      applyTypewriterEffect(node);
    }
  });

  // 设置每个字符的动画延迟,控制打字速度
  const allChars = element.querySelectorAll(".char");
  allChars.forEach((char, index) => {
    char.style.animationDelay = `${index * 0.04}s`; // 数值越小打字越快
  });
}

// 初始化动画
const typeWriterEl = document.querySelector(".type-writer");
applyTypewriterEffect(typeWriterEl);
</script>
</body>
</html>

关键说明

  • 递归遍历子元素:确保所有嵌套标签(如<h1>、<a>)内的文本都能被拆分并应用动画;
  • 字符级精准控制:通过animationDelay逐个延迟字符显示,还原真实打字节奏,可自行调整延迟数值改变速度;
  • 自适应多行:容器设置max-width触发自动换行,字符会跟随浏览器换行规则逐行展示;
  • 全局光标动画:用伪元素实现持续闪烁的打字光标,无需额外DOM元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 08:53:25