循环打字机效果实现求助:无法清屏、文本堆叠及<h1>文本漏字问题
解决打字机效果的两个问题(文本堆叠+单词不显示)
看起来你遇到的两个核心问题:一是文本堆叠没法清空上一句,二是单词"the"丢失,还要保留HTML里的文本方便复用脚本。我给你一套完整的解决方案,直接复用即可:
第一步:HTML结构(保留可复用文本)
首先我们把每个句子用<span class="sentence">包裹,这样脚本可以轻松提取所有句子,同时你在不同页面只需要修改这些span里的内容就行,不用动脚本:
<h1 id="typewriter"> <span class="sentence">Hello, this is the first test sentence.</span> <span class="sentence">The second sentence clearly shows the word 'the'.</span> <span class="sentence">After this final sentence, we'll loop back to the start.</span> </h1>
第二步:添加光标动画(增强打字机体验)
加一点点CSS让打字机有闪烁光标效果,更真实:
#typewriter::after { content: "|"; animation: blink 1s step-end infinite; } @keyframes blink { from, to { opacity: 1; } 50% { opacity: 0; } }
第三步:核心JS脚本(解决两个问题)
这个脚本会处理逐字打印、清空上一句、循环逻辑,同时确保所有字符(包括"the")都正常显示:
const typewriterEl = document.getElementById('typewriter'); // 提取所有句子并隐藏原始span,避免干扰显示 const sentences = Array.from(typewriterEl.querySelectorAll('.sentence')).map(sentence => { sentence.style.display = 'none'; return sentence.textContent.trim(); }); let currentSentenceIndex = 0; let currentCharIndex = 0; const typingSpeed = 100; // 每个字符的打印速度(毫秒) const pauseAfterSentence = 2000; // 打完句子后停留的时间 const eraseSpeed = 50; // 逐字清空的速度 function typeSentence() { const currentSentence = sentences[currentSentenceIndex]; if (currentCharIndex < currentSentence.length) { // 逐字添加文本,确保每个字符(包括空格、"the")都被处理 typewriterEl.textContent += currentSentence.charAt(currentCharIndex); currentCharIndex++; setTimeout(typeSentence, typingSpeed); } else { // 打完句子后,等待一段时间再开始清空 setTimeout(eraseSentence, pauseAfterSentence); } } function eraseSentence() { if (typewriterEl.textContent.length > 0) { // 逐字清空文本,避免直接设置为空的突兀感 typewriterEl.textContent = typewriterEl.textContent.slice(0, -1); setTimeout(eraseSentence, eraseSpeed); } else { // 切换到下一句,通过取模实现循环 currentSentenceIndex = (currentSentenceIndex + 1) % sentences.length; currentCharIndex = 0; setTimeout(typeSentence, typingSpeed); } } // 启动打字机效果 typeSentence();
关键问题的解决说明:
解决文本堆叠问题:
我们专门写了eraseSentence函数,在打完当前句子后,逐字清空容器内容,而不是直接覆盖。清空完成后才会开始打印下一句,彻底避免堆叠。解决"the"不显示问题:
脚本直接使用每个句子的textContent,没有做任何单词过滤或字符跳过逻辑,所有字符(包括空格、常用单词)都会被逐字打印,所以"the"肯定能正常显示。保留HTML文本复用性:
所有需要展示的句子都放在HTML的<span class="sentence">里,你在不同页面使用时,只需要修改这些span的内容,完全不用改动JS脚本,非常方便复用。
内容的提问来源于stack exchange,提问作者replicant129
相关产品推荐
相关产品推荐

