纯js实现打字机效果

Elaine ·
更新时间:2024-09-21
· 1068 次阅读

本文实例为大家分享了js实现打字机效果的具体代码,供大家参考,具体内容如下

效果图

应用场景

用处不大,只是看到网上有类似的效果,写了四五十行看不懂的代码,于是尝试能不能简单的实现

html

<h2 id="text-box"></h2> <!--一行也是代码--> css h2 { width: 800px; line-height: 40px; border-bottom: 1px solid; margin: 200px auto; font-size: 24px; } .animate { display: inline-block; padding: 0 5px; vertical-align: 3px; font-size: 20px; font-weight: normal; } .animate.on { animation: fade 1.5s infinite forwards; } @keyframes fade { from { opacity: 0; } to { opacity: 1; } }

js

let textBox = $('#text-box'); let index = 0; let str = 'Welcome to my website!'; let len = str.length; function input() { textBox.html(str.substr(0, index) + '<span class="animate">|</span>'); setTimeout(function() { index++; if(index === len + 1) { $('.animate').addClass('on'); return; } input(); }, Math.random() * 600) console.log(index); } input(); 实现原理

通过定时器结合字符串截取实现类似于打字机的顿挫感,并通过递归累加index。相当于第1s时,截取一个字节,第二秒时,截取两个字节,以此类推……定时器时间取随机数,模拟打字的停顿感更好。递归调用中加结束循环条件,结束之前启动动画,模拟光标的跳动。



js实现 打字机 js

需要 登录 后方可回复, 如果你还没有账号请 注册新账号