[前端] 纯html+css实现打字效果

2409 0
黑夜隐士 2022-10-19 15:40:21 | 显示全部楼层 |阅读模式
本文主要介绍了纯html+css实现打字效果,具有一定的参考价值,感兴趣的可以了解一下
效果图


分析


可以将动画看做三个不同的层次:
    最底层的文字中间挡住文字的背景最上层的光标
文字是静止的,而中间的背景和最上层的光标是动态的。
初始时,背景挡住所有的文字,光标在最左边。
动画进行时,背景和光标以相同的步伐从左往右移动。
动画结束时,背景不再遮挡文字,光标则在最右边闪烁。


代码


html
  1. <div class="text">hello,world!</div>
复制代码
css
  1. :root {
  2.     /* 字符数量 */
  3.     --steps: 12;
  4.     /* 动画时间 */
  5.     --duration: 2.5s;
  6.     /* 字体大小 */
  7.     --fontSize: 50px;
  8.     /* 光标大小 */
  9.     --cursorSize: 20px;
  10. }
  11. .text {
  12.     color: #333;;
  13.     position: relative;
  14.     display: inline-block;
  15.     font-family: 'Courier New', Courier, monospace;
  16.     font-size: var(--fontSize);
  17.     line-height: 1;
  18. }
  19. .text::after {
  20.     content: '';
  21.     width: var(--cursorSize);
  22.     height: var(--fontSize);
  23.     background-color: black;
  24.     z-index: 2;
  25.     position: absolute;
  26.     animation: blink 1s var(--duration) step-end infinite,
  27.                moveCursor var(--duration) steps(var(--steps)) forwards;
  28. }
  29. .text::before {
  30.     content: '';
  31.     width: 100%;
  32.     height: var(--fontSize);
  33.     z-index: 1;
  34.     position: absolute;
  35.     background: linear-gradient(#fff, #fff) no-repeat top right;
  36.     animation: showText var(--duration) steps(var(--steps)) forwards;
  37. }
  38. /* 光标闪烁动画 */
  39. @keyframes blink {
  40.     0% {
  41.         background-color: black;
  42.     }
  43.     50% {
  44.         background-color: transparent;
  45.     }
  46.     100% {
  47.         background-color: black;
  48.     }
  49. }
  50. /* 光标移动动画 */
  51. @keyframes moveCursor {
  52.     0% {
  53.         left: 0%;
  54.     }
  55.     100% {
  56.         left: 100%;
  57.     }
  58. }
  59. /* 背景移动动画 */
  60. @keyframes showText {
  61.     0% {
  62.         background-size: 100% 100%;
  63.     }
  64.     100% {
  65.         background-size: 0% 100%;
  66.     }
  67. }
复制代码
注意
字体必须是等宽字体。因为光标每次移动的距离是是根据字符的数量 / 总宽度来决定的。

在线演示

到此这篇关于纯html+css实现打字效果的文章就介绍到这了,更多相关html css打字效果内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章,希望大家以后多多支持中国红客联盟!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行