JavaScript打字效果故障:无法模拟输入错误并输出正确Welcome
问题分析与修复
你的代码输出Wlcome而非预期Welcome的原因很明确:在removeX函数里,你把currentIndex设成了2,而textToType的索引1对应的正是缺失的那个e——直接跳到索引2就会跳过这个字符。
修复步骤
只需要修改removeX函数里的currentIndex赋值,把2改成1:
function removeX() { const currentText = element.innerHTML; element.innerHTML = currentText.slice(0, -1); currentIndex = 1; // 这里从2改成1 setTimeout(typeLetter, typingSpeed); }
完整修复后的代码
下面是整合好的完整HTML文件,直接运行就能得到预期效果:
<!DOCTYPE html> <html> <head> <title>Typing Example</title> <style> #typing-area::after { content: ''; display: inline-block; width: 0.1em; animation: blink 1s infinite; } @keyframes blink { 50% { opacity: 0; } } </style> </head> <body> <div id="typing-area"></div> <script> const element = document.querySelector('#typing-area'); let textToType = 'Welcome'; const delayTime = 1000; const typingSpeed = 100; let currentIndex = 0; function typeLetter() { const currentText = element.innerHTML; if (currentIndex === 1) { element.innerHTML += 'x'; setTimeout(removeX, 1000); } else { element.innerHTML = currentText + textToType[currentIndex]; currentIndex++; if (currentIndex < textToType.length) { setTimeout(typeLetter, typingSpeed); } } } function removeX() { const currentText = element.innerHTML; element.innerHTML = currentText.slice(0, -1); currentIndex = 1; // 修正此处的索引值 setTimeout(typeLetter, typingSpeed); } setTimeout(typeLetter, 500); </script> </body> </html>
修复逻辑说明
- 输入完
W后,currentIndex变为1,此时临时插入x并触发删除操作 - 删除
x后,把currentIndex重置为1,后续typeLetter会从textToType的第1位(即e)开始继续输入 - 之后依次输入剩余字符,最终得到完整的
Welcome
内容的提问来源于stack exchange,提问作者Jane Laville
相关产品推荐
相关产品推荐

