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

如何为随机名言生成器添加打字机动画效果?

实现简单的随机名言打字机动画

这里给你一个极简的纯JS方案,不用依赖任何库,直接修改你的现有代码就能实现需求:

完整代码

<p id="quotetxt"></p>
<button id="generate">generate</button>

<script>
// 把名言数组放在全局,避免重复创建
const quotes = [
  { quote: "Here's a text" },
  { quote: "Here's another one" },
  { quote: "Lorem ipsum bla bla" },
  { quote: "I can do this all day" }
];

// 用于管理打字定时器,防止多个动画同时运行
let typeTimer = null;

// 打字机动画函数
function typeText(element, text, speed = 50) {
  // 先清除之前的定时器,避免混乱
  if (typeTimer) clearInterval(typeTimer);
  
  // 清空目标元素内容
  element.innerHTML = '';
  let charIndex = 0;
  
  // 启动定时器,逐个添加字符
  typeTimer = setInterval(() => {
    if (charIndex < text.length) {
      element.innerHTML += text.charAt(charIndex);
      charIndex++;
    } else {
      // 字符全部添加完成,清除定时器
      clearInterval(typeTimer);
      typeTimer = null;
    }
  }, speed);
}

const generateQuote = function() {
  let arrayIndex = Math.floor(Math.random() * quotes.length);
  const targetElement = document.getElementById("quotetxt");
  // 调用打字动画函数显示选中的名言
  typeText(targetElement, quotes[arrayIndex].quote);
}

window.onload = function loadquote() {
  generateQuote();
  document.getElementById("generate").addEventListener('click', generateQuote);
}
</script>

关键逻辑说明

  • 全局名言数组:把quotes移到函数外面,每次生成名言时不用重复创建数组,提升效率。
  • 定时器管理:用typeTimer变量保存定时器实例,每次开始新动画前先清除旧定时器,解决你之前遇到的字符乱序问题——避免多次点击按钮时多个动画同时运行叠加字符。
  • 打字机核心函数:typeText函数负责逐个字符添加到目标元素里,通过setInterval控制字符出现的速度(默认50毫秒/字符,你可以自己调整这个数值),当所有字符都显示完成后自动停止定时器。
  • 修改生成逻辑:原来的generateQuote不再直接赋值文本,而是调用typeText来实现动画显示。

这个方案完全基于你现有的代码修改,逻辑简单易懂,适合JS新手调试和修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 16:22:49