纯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时,截取一个字节,第二秒时,截取两个字节,以此类推……定时器时间取随机数,模拟打字的停顿感更好。递归调用中加结束循环条件,结束之前启动动画,模拟光标的跳动。

猜你喜欢

转载自blog.csdn.net/dizuncainiao/article/details/81365039
今日推荐