23

纯 CSS3 实现打字/输入的效果 | Ftopia

 3 years ago
source link: https://ftopia.cn/2020/cssforprinter/?
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

纯 CSS3 实现打字/输入的效果

  By me ♥   2020-06-04   539 字   2 分钟

若在网页总实现打字/输入效果,可使用纯CSS的方式实现,不多说,动图效果如下:

cssForPrinter

适用场景:页面中希望被注意的文字,标题、引文、博客标语等;HTML5 中炫酷的打字效果实现 ~

参考文章: 小tips: 纯CSS实现打字动画效果 By 张鑫旭

Talk is cheap. Show me the code. 不想看文章的直接 →_→ CodeSandBox Example

示例中区分了纯中文 & 中英文混合两种,原因在于中英文(符号)的字符宽度不同,中英文混合的代码参考如下:

 <p class="typing-e">中英文 Printer 效果,字符宽度 18.5</p>
.typing-e {
  width: 18.5em;
  height: 1.25em;
  border-right: 1px solid transparent;
  animation: typing-e 3.5s steps(37, end), blink-caret 0.75s step-end infinite;
  font-family: Consolas, Monaco;
  word-break: break-all;
  overflow: hidden;
}

@keyframes typing-e {
  from {
    width: 0;
  }
  to {
    width: 18.5em;
  }
}

@keyframes blink-caret {
  from,
  to {
    border-color: transparent;
  }
  50% {
    border-color: currentColor;
  }
}

可以看出实现还是相对简单的,纯 CSS 实现需要定下字符宽度(示例中为 18.5em)。

原理?通过改变容器宽度实现,border-right 实现光标样式,加之 CSS3 animation 的动画实现效果。

列出相关的技术点:

  • font-family: Consolas, Monaco; 等宽字体便于宽度计算
  • animation <step-timing-function> 方式实现
<step-timing-function> = step-start | step-end | steps(<integer>[, <step-position>]?)

上述仅仅是实现了单行定宽文字的效果,可考虑研究下多行的效果呈现(如古诗词、名人名言等 ✨)

配合 JS、Less 等可实现较为通用的方式/方法(不用确认宽度,自动计算)

如需更炫酷,可考虑加文字变大 or 色彩动画等(但觉得可能会过犹不及)


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK