打字效果插件 typing.js

Demo Demo2

typeit

一个 JS 库,用来在网页上生成打字机输入文字的动画效果。

react 实现

  1. import { useState } from 'react';
  2. import { Button } from 'antd';
  3. import { useInterval } from 'ahooks';
  4. import styles from './index.less';
  5. const timing = 250;
  6. const typingList = '欢迎使用,食安校园;食者无忧,管着有方!欢迎使用,食安校园;食者无忧,管着有方!欢迎使用,食安校园;食者无忧,管着有方!'.split('');
  7. export default function IndexPage() {
  8. const [typingIdx, setTypingIdx] = useState(-1);
  9. const [interval, setInterval] = useState<number | undefined>(undefined);
  10. // 自动轮播
  11. useInterval(() => {
  12. setTypingIdx((prev) => {
  13. if (prev >= typingList.length - 1) {
  14. setInterval(undefined);
  15. return prev;
  16. }
  17. return prev + 1;
  18. });
  19. }, interval);
  20. const onTyping = () => {
  21. setInterval(timing);
  22. };
  23. return (
  24. <div className={styles.admin}>
  25. <Button onClick={onTyping}>开始打字</Button>
  26. <div className={styles.typingContent}>
  27. {typingList.map((item, index) => (index <= typingIdx ? item : null))}
  28. <span className={styles.cursor} />
  29. </div>
  30. </div>
  31. );
  32. }

无 JS 实现打字效果

转载:CSS 技巧 - Marko Denic
html 文件

  1. <div class="wrapper">
  2. <div class="typing-demo">This is a typing demo.</div>
  3. </div>

css 文件

  1. .wrapper {
  2. height: 100vh;
  3. /*This part is important for centering*/
  4. display: flex;
  5. align-items: center;
  6. justify-content: center;
  7. }
  8. .typing-demo {
  9. width: 22ch;
  10. animation: typing 2s steps(22), blink .5s step-end infinite alternate;
  11. white-space: nowrap;
  12. overflow: hidden;
  13. border-right: 3px solid;
  14. font-family: monospace;
  15. font-size: 2em;
  16. }
  17. @keyframes typing {
  18. from {
  19. width: 0
  20. }
  21. }
  22. @keyframes blink {
  23. 50% {
  24. border-color: transparent
  25. }
  26. }