React.js中Interval循环一次后设置Timeout的打字效果问题
解决打字循环效果中光标停留2秒的问题
我刚好折腾过类似的循环打字效果,你的问题核心是要在第一句打字完成后,让光标多停留一会儿再切换句子对吧?给你分享个亲测有效的实现方案,分代码和逻辑拆解两部分:
核心实现代码
先上完整的可运行代码,你可以直接套进去改内容:
HTML结构
<div class="typewriter-container"> <span class="typed-text"></span> <span class="blinker">|</span> </div>
CSS样式(控制光标闪烁)
.typewriter-container { font-size: 24px; font-family: monospace; } .blinker { animation: blink 1s infinite; } @keyframes blink { 0%, 50% { opacity: 1; } 51%, 100% { opacity: 0; } }
JavaScript逻辑(核心控制)
const sentences = ["第一句要显示的文本", "第二句循环的内容", "第三句也可以加进来"]; const typedTextElement = document.querySelector(".typed-text"); const blinkerElement = document.querySelector(".blinker"); let currentSentenceIndex = 0; let currentCharIndex = 0; let typingSpeed = 150; // 打字速度,单位毫秒 function typeSentence() { const currentSentence = sentences[currentSentenceIndex]; // 逐字打字逻辑 if (currentCharIndex < currentSentence.length) { typedTextElement.textContent += currentSentence.charAt(currentCharIndex); currentCharIndex++; setTimeout(typeSentence, typingSpeed); } else { // 打字完成后,让光标停留2秒 setTimeout(() => { // 清除当前句子 deleteSentence(); }, 2000); // 这里的2000就是停留的2秒 } } function deleteSentence() { const currentSentence = sentences[currentSentenceIndex]; // 逐字删除逻辑 if (currentCharIndex > 0) { typedTextElement.textContent = currentSentence.substring(0, currentCharIndex - 1); currentCharIndex--; setTimeout(deleteSentence, 100); // 删除速度可以调整 } else { // 切换到下一句,循环回去 currentSentenceIndex = (currentSentenceIndex + 1) % sentences.length; typeSentence(); } } // 启动效果 typeSentence();
关键逻辑拆解
- 打字完成后的停留控制:在
typeSentence函数里,当判断当前句子的所有字符都打完后,用setTimeout延迟2秒再执行删除句子的操作,这期间光标会保持闪烁状态(因为CSS的动画一直在运行)。 - 循环切换句子:用取模运算
(currentSentenceIndex + 1) % sentences.length实现句子的循环切换,不会越界。 - 光标状态保持:整个过程中光标元素的CSS动画一直生效,所以停留期间光标会正常闪烁,直到开始删除句子后才会随着文本一起消失(或者你也可以在删除前先隐藏光标,看需求调整)。
如果你的现有代码是用其他框架(比如React/Vue)实现的,核心逻辑也是一样的:在打字完成的回调里加一个2秒的延迟,再执行切换操作就行。
内容的提问来源于stack exchange,提问作者Murakami
相关产品推荐
相关产品推荐

