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

如何用jQuery实现网页字符串逐字符反向删除效果?

解决打字机效果的反向删除问题

嘿,我来帮你搞定这个反向删除的问题!你之前用replace结合setInterval操作text()没成功,大概率是因为没正确管理定时器,或者删除逻辑的实现方式不够可靠——比如replace可能会因为匹配规则、多次触发的定时器导致异常。

先看看优化后的完整方案,既能完成逐字符输入,又能实现反向删除,甚至还能做成循环往复的效果:

$(function() {
  // 缓存目标span元素,减少重复DOM查询
  const targetSpan = $('.main_section_animate span');
  const displayText = "Coming Soon|";
  let currentCharIndex = 0;
  let animationTimer;

  // 逐字符输入函数
  function typeCharacters() {
    animationTimer = setInterval(() => {
      if (currentCharIndex < displayText.length) {
        // 追加当前字符
        targetSpan.append(displayText[currentCharIndex]);
        currentCharIndex++;
      } else {
        // 输入完成后停止定时器,延迟1秒启动删除
        clearInterval(animationTimer);
        setTimeout(deleteCharacters, 1000);
      }
    }, 100);
  }

  // 反向逐字符删除函数
  function deleteCharacters() {
    animationTimer = setInterval(() => {
      const currentContent = targetSpan.text();
      if (currentContent.length > 0) {
        // 截取前length-1个字符,稳定实现删除最后一个字符的效果
        targetSpan.text(currentContent.slice(0, -1));
      } else {
        // 删除完成后停止定时器,可选:延迟1秒再次启动输入,形成循环动画
        clearInterval(animationTimer);
        currentCharIndex = 0;
        setTimeout(typeCharacters, 1000);
      }
    }, 100);
  }

  // 启动打字机动画
  typeCharacters();
})

关键优化点说明:

  • 定时器管理:用clearInterval在输入/删除完成时停止定时器,避免多个定时器同时运行导致的文本混乱
  • 可靠的删除逻辑:用slice(0, -1)直接截取当前文本的前n-1个字符,比replace更稳定,不会因为特殊字符或匹配规则出问题
  • DOM性能优化:提前缓存目标span元素,避免每次定时器触发都重复查询DOM
  • 流程控制:输入完成后延迟1秒再删除,删除完成后也可以选择循环触发输入,让动画节奏更自然

如果不需要循环效果,只需要输入一次再删除一次,删掉删除函数里的setTimeout(typeCharacters, 1000)和currentCharIndex = 0就行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 09:42:35