如何在网站中实现打字机效果,修复现有代码光标异常、运行过慢问题
问题修复方案
你当前代码的光标占满段落、打字过慢问题,根源在于原方案是基于单行文本的横向遮罩实现,不适配多行文本,且延迟参数设置过大。我们直接用你提到的「字符数组遍历+光标模拟」的思路实现,逻辑更简单,更易学习。
修复后的完整代码
HTML代码
<div id="box_1"> <img id="box_1_img" src="/images/artmainpage/pic1.jpg" alt="Image cannot be displayed"> <div id="box_1_para"> <span class="text1"></span> <span class="text_cursor">|</span> </div> </div>
CSS代码
#box_1 { grid-area: b; border: 1px dotted red; margin: 2px; display: flex; align-items: center; justify-content: space-around; } #box_1_img { margin-left: 10px; height: 80%; filter: blur(1px); background: rgba(255,255,255,0.1); backdrop-filter: blur(6px); transition: all .5s ease-in-out; } #box_1_img:hover { margin-left: 10px; height: 90%; transition: all .5s ease-in-out; filter: blur(0px); } *{ margin: 0; padding: 0; box-sizing: border-box; } #box_1_para { margin-left: 10px; margin-right: 10px; font-family: 'Courier New', Courier, monospace; font-size: small; line-height: 1.5; width: 60%; } .text_cursor { animation: blink 0.7s infinite; } @keyframes blink { 0%, 70% { opacity: 1; } 71%, 100% { opacity: 0; } }
JS代码
const originText = "Cras egestas porttitor ante, ut iaculis nulla facilisis sit amet. Pellentesque tristique erat est, eget consectetur nunc pulvinar vel. Aliquam vel lorem et massa auctor dictum vitae at tellus. Suspendisse potenti."; const textElement = document.querySelector(".text1"); const typeSpeed = 50; // 打字速度单位ms,数值越小速度越快 let charIndex = 0; function typingAnimation() { if (charIndex < originText.length) { textElement.textContent += originText.charAt(charIndex); charIndex++; setTimeout(typingAnimation, typeSpeed); } else { setTimeout(() => { charIndex = 0; textElement.textContent = ""; typingAnimation(); }, 1000); // 打字完成后停留1秒再重置循环 } } typingAnimation();
修改说明
- 光标问题:光标改为跟在文本后的行内元素,高度和文本行高一致,不会出现占满整个段落的问题,自带原生闪烁效果
- 速度问题:通过
typeSpeed参数直接控制打字速度,默认50ms输出一个字符,可根据需求自由调整 - 逻辑简化:完全采用你提到的字符数组遍历思路,没有复杂的动画计算,易读易修改,方便学习
- 兼容性:天生支持多行文本,不需要额外适配不同长度的文本内容
- 原有图片悬停变清晰的效果完全保留,没有改动
内容的提问来源于stack exchange,提问作者snowleopard
相关产品推荐
相关产品推荐

