Typewriter animation is a very common animation effect, and there are many ways to achieve it
Recently, I just encountered a similar demand in the project. I have sorted out a few methods to realize animation and shared it~
method one,
The best typewriter animation
Add or subtract text through the js timer, and use a separate label to write cursor animation, so that even if the text wraps, it can be presented well
HTML
<div class="typing"> <span class="typing-text">This is a legendary typing animation</span> <i class="caret"></i> </div>
CSS
.caret::after { content: ""; display: inline-block; width: 2px; height: 1em; margin-bottom: -2px; margin-left: -2px; background-color: #333; animation: blink-caret .5s step-end infinite; } @keyframes blink-caret { 50% {opacity: 0;} }
JS
var box = document.getElementsByClassName('typing-text')[0]; var str = box.innerText; var i = 0; box.innerText = ''; var typing = setInterval(function() { box.innerText + = str [i ++]; i >= str.length && clearInterval(typing); }, 200);
Method Two,
The method found on the Internet, animation made by pure CSS3
By limiting the width with overflow:hidden to achieve the effect of adding text, use the border as the cursor
<style type="text/css"> .typing { border-right: .1em solid; width: 9em; /*width is "number of words + em"*/ white-space: nowrap; overflow: hidden; animation: typing 5s steps(9, end), /*The number of steps is the number of words*/ blink-caret .5s step-end infinite alternate; } @keyframes typing { from { width: 0; } } @keyframes blink-caret { 50% { border-color: transparent; } } </style> <div class="typing">This is a typewriter animation</div>
The advantage of this method is that you don't need to write js, but there are many limitations:
For example, the text cannot wrap automatically, and the element width needs to be set manually.
When the text is in English, a monospaced font such as Consolas must be used