如何修改jsfiddle代码实现搜索框占位符多短语循环打字动画?
实现搜索框占位符多短语循环打字动画
嘿,我懂你想要的效果——让搜索框的占位符像打字机一样依次展示多个短语,循环往复对吧?这其实只需要在原来的单短语动画基础上,加个短语数组和循环切换的逻辑就行。我给你整理了完整的实现代码,还加了注释方便你理解:
完整代码实现
HTML
<input type="text" id="searchInput" placeholder="" />
CSS
#searchInput { padding: 8px 12px; font-size: 16px; border: 1px solid #ddd; border-radius: 4px; width: 300px; }
JavaScript
const searchInput = document.getElementById('searchInput'); // 这里放你想要循环展示的短语数组,随便加多少个都行 const phrases = ["搜索技术文档", "查找开发教程", "探索开源项目", "检索解决方案"]; let currentPhraseIndex = 0; let currentCharIndex = 0; const typeSpeed = 150; // 打字速度(毫秒/字符) const deleteSpeed = 100; // 删除速度(毫秒/字符) const pauseBetweenPhrases = 2000; // 每个短语展示后的停顿时间(毫秒) // 打字函数:逐个字符添加到占位符 function typePhrase() { if (currentCharIndex < phrases[currentPhraseIndex].length) { searchInput.placeholder += phrases[currentPhraseIndex].charAt(currentCharIndex); currentCharIndex++; setTimeout(typePhrase, typeSpeed); } else { // 打完当前短语后,停顿一会儿再开始删除 setTimeout(deletePhrase, pauseBetweenPhrases); } } // 删除函数:逐个字符删除占位符内容 function deletePhrase() { if (currentCharIndex > 0) { searchInput.placeholder = searchInput.placeholder.slice(0, -1); currentCharIndex--; setTimeout(deletePhrase, deleteSpeed); } else { // 删除完后切换到下一个短语,索引循环回到开头 currentPhraseIndex = (currentPhraseIndex + 1) % phrases.length; // 停顿一小会儿开始打下一个短语 setTimeout(typePhrase, 500); } } // 启动动画 typePhrase();
关键逻辑说明
- 短语数组:
phrases里可以放任意数量的你想要展示的文本,后续要加新短语直接往数组里加就行。 - 状态跟踪:用
currentPhraseIndex记录当前正在展示的短语下标,currentCharIndex记录当前正在处理的字符位置。 - 循环切换:删除完一个短语后,通过
(currentPhraseIndex + 1) % phrases.length实现索引的循环(比如最后一个短语之后回到第一个)。 - 节奏控制:几个速度变量
typeSpeed、deleteSpeed、pauseBetweenPhrases可以根据你的需求调整,让动画节奏更舒服。
你可以直接把这段代码替换掉原来的代码,就能看到多短语循环打字的效果啦!
内容的提问来源于stack exchange,提问作者Ben Nalle
相关产品推荐
相关产品推荐

