这篇文章告诉你如何使用HTML+CSS来实现打字的效果。
1.如何使用Html+CSS实现打字效果
- 你可以认为打字效果有3层。
- 底层是文本层。
- 中间层是覆盖文本的背景。
- 最上面的一层显示光标。
- 文本层是静态的,而中间层的背景和顶部层的光标是动态的。
- 最初,背景覆盖了所有的文字,光标在最左边的位置。
- 随着动画的进行,背景和光标以同样的速度从左到右移动。
- 在动画结束时,背景不再覆盖文本,光标在最右边的点上闪烁。
2.示例源代码
-
创建一个Html文件implement_typing_effect_use_html_css.html。
-
复制并粘贴以下Html源代码到上述文件中。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Implement Typing Effect Use Html + CSS</title> <style> :root { /* number of characters in the displayed string in the html div element. */ --steps: 56; /* animation duration, the total time that will cost to print the text string. */ --duration: 10s; /* font size */ --fontSize: 50px; /* cursor size */ --cursorSize: 20px; } .text { color: #333;; position: relative; display: inline-block; font-family: 'Courier New', Courier, monospace; font-size: var(--fontSize); line-height: 1; } .text::after { content: ''; width: var(--cursorSize); height: var(--fontSize); background-color: black; z-index: 2; position: absolute; animation: blink 1s var(--duration) step-end infinite, moveCursor var(--duration) steps(var(--steps)) forwards; } .text::before { content: ''; width: 100%; height: var(--fontSize); z-index: 1; position: absolute; background: linear-gradient(#fff, #fff) no-repeat top right; animation: showText var(--duration) steps(var(--steps)) forwards; } /* Cursor blink animation */ @keyframes blink { 0% { background-color: black; } 50% { background-color: transparent; } 100% { background-color: black; } } /* Cursor move animation */ @keyframes moveCursor { 0% { left: 0%; } 100% { left: 100%; } } /* background move animation */ @keyframes showText { 0% { background-size: 100% 100%; } 100% { background-size: 0% 100%; } } </style> </head> <body> <div class="text">This typing effect is implemented use Html & CSS!</div> </body> </html>