打字机效果

Avatar of Geoff Graham
Geoff Graham
.typewriter h1 {
  overflow: hidden; /* Ensures the content is not revealed until the animation */
  border-right: .15em solid orange; /* The typwriter cursor */
  white-space: nowrap; /* Keeps the content on a single line */
  margin: 0 auto; /* Gives that scrolling effect as the typing happens */
  letter-spacing: .15em; /* Adjust as needed */
  animation: 
    typing 3.5s steps(40, end),
    blink-caret .75s step-end infinite;
}

/* The typing effect */
@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}

/* The typewriter cursor effect */
@keyframes blink-caret {
  from, to { border-color: transparent }
  50% { border-color: orange; }
}

笔记

  • 演示依赖于 flexbox,因此在测试中可能会影响布局
  • 假设使用 Autoprefixer
  • 文本容器的宽度将由所用文本的长度决定
  • typing 动画中添加更多步骤将增加打字的平滑度
  • 根据所使用的字体系列和字号调整 letter-spacing

更多!

有些人使用 JavaScript,这有时可能更可取(逐个字符地添加文字感觉更像真实的打字机),有时则不然(潜在的可访问性问题)。

Typed.css

Brandon McConnell 那里发现了 这个 SCSS @mixin,它具有强大的选项,可以识别多个字符串、速度、插入符号配置、暂停以及其他各种功能。