Pure js realizes the typewriter effect

Effect picture

Application scenarios

It's not very useful. I just saw a similar effect on the Internet. I wrote 40 or 50 lines of code that I didn't understand, so I tried to make it simple.

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();

Realization principle

Combine the timer with string interception to achieve a sense of frustration similar to a typewriter, and accumulate the index through recursion. It is equivalent to intercepting one byte in the first second, and intercepting two bytes in the second second, and so on... The timer time is a random number, and the simulated typing has a better pause. Add the end loop condition in the recursive call, start the animation before the end, and simulate the beating of the cursor.

Guess you like

Origin blog.csdn.net/dizuncainiao/article/details/81365039