实现反向打字效果遇问题:重复删除及延迟展示需求
解决方案
问题分析
你的代码存在三个核心问题:
- 初始逻辑错误:未先完整显示"Coming Soon",反而直接开始删除字符
- 删除无终止条件:
remove变量始终为false,导致索引持续递减到负数,视觉上出现重复删除效果 - 缺少延迟显示和后续输入新文本的逻辑
修正后的代码
<p id="demo"></p>
const demoEl = document.getElementById("demo"); const initialText = 'Coming Soon'; const finalText = 'SeaDogs.com.eu.as'; const typeSpeed = 520; // 单个字符操作的间隔毫秒数 const displayDelay = 3000; // 初始文本的停留时长 // 阶段控制:0=显示初始文本并等待,1=反向删除初始文本,2=正向输入最终文本 let currentPhase = 0; let currentIndex = 0; function typeEffect() { switch(currentPhase) { case 0: // 先渲染完整的初始文本,再进入延迟等待 demoEl.textContent = initialText; currentPhase = 1; setTimeout(typeEffect, displayDelay); break; case 1: // 反向删除:从文本末尾逐步截短 const deleteEndIndex = initialText.length - 1 - currentIndex; demoEl.textContent = initialText.slice(0, deleteEndIndex); currentIndex++; // 删完所有字符后,切换到输入阶段 if(currentIndex > initialText.length) { currentPhase = 2; currentIndex = 0; } setTimeout(typeEffect, typeSpeed); break; case 2: // 正向输入:逐步扩展最终文本的显示范围 demoEl.textContent = finalText.slice(0, currentIndex + 1); currentIndex++; // 输入完成后停止定时器 if(currentIndex >= finalText.length) { return; } setTimeout(typeEffect, typeSpeed); break; } } // 启动打字效果 typeEffect();
关键改进点
- 阶段化逻辑:用
currentPhase明确区分三个操作阶段,避免逻辑混乱 - 明确终止条件:删除阶段在索引超过文本长度时自动切换到输入阶段,解决重复删除问题
- 延迟显示:初始文本完整显示后,通过
displayDelay控制停留时长 - 安全渲染:使用
textContent代替innerHTML,避免不必要的HTML解析风险
内容的提问来源于stack exchange,提问作者brokefacebaby
相关产品推荐
相关产品推荐

