Overview
Long ago in other people's blog above to see the typing animation , feel very cool, thought is to do with JS, find a half-day also did not find JS where. Today, see the "CSS secret", happened to see the book on the realization of the typing animation, and is a pure CSS implementation! I refer to this book to record the Code for future development, I believe that other people also useful.
Code
The CSS code in the book is this:
@keyframes typing { from { width: 0 } /* 从左到右的动画 */}@keyframes caret { 50% { border-color: transparent; } /* 闪烁动画 */}h1 { width: 15ch; /* 文本的宽度 */ overflow: hidden; white-space: nowrap; border-right: .05em solid; animation: typing 6s steps(15), caret 1s steps(1) infinite;}
JS implementation
Sometimes, it is very inconvenient to add CSS to the Web page, if written in the form of JS plug-in will be convenient, the following code is I put the above CSS code into the form of plug-ins:
(function () {var timing = 15,//Set animation time in seconds userclass = "#blog_news_aboutme",//Set animation Label class Isenglish = true; Chinese characters and English are not supported; Chinese characters fill false, English fill true//Add style tag var rule = "@keyframes typing {from {width:0;}} @keyframes Caret {50% {border-color:transparent;}} "+ UserClass +" {width:32em; overflow:hidden; white-space:nowrap; Border-right:. 05em solid; animation:typing "+ Tim ing + "s steps (+) infinite, caret 1s steps (1) infinite;}"; var style = document.createelement (' style '); Style.type = ' text/css '; style.innerhtml = rule; document.getElementsByTagName (' head ') [0].appendchild (style); Native Tool function $$ (selector, context) {context = context | | document; var elements = Context.queryselectorall (selector); return Array.prototype.slice.call (elements); }//Change the animation $$ (' H1 ') by the number of words. ForEach (function (H1) {var len = h1.textContent.length + 1, s = h1.style; var unit = Isenglish? ' ch ': ' em '; S.width = (len + 0.08) + unit; S.animationtimingfunction = "Steps (" + LEn + "), Steps (1)"; });}) ()
Just follow the comments to modify timing,userclass and isenglish These three parameters, and then introduce JS into the Web page, you can achieve the typing effect.
Please refer to the bulletin board in the top left corner of my blog for specific results. (can only use the PC side to see, the mobile phone side does not see Oh!) )
Other
Of course, there are big God with JS to achieve the typing effect and made a plug-in, the specific can see this plugin termynal.
Pure CSS for typing effect