Skip to content

如何实现一个页面自动打字效果

方法一:使用纯 JavaScript 实现打字效果

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>自动打字效果</title>
  <style>
    .typewriter-text {
      font-family: 'Courier', monospace;
      font-size: 24px;
      white-space: pre;
      border-right: 2px solid;
      width: fit-content;
      animation: caret-blink 0.7s infinite;
    }

    @keyframes caret-blink {
      50% {
        border-color: transparent;
      }
    }
  </style>
</head>
<body>

  <div id="typewriter" class="typewriter-text"></div>

  <script>
    const text = "这是一个自动打字效果的示例。";  // 你想要显示的文字
    const speed = 100;  // 速度,毫秒
    let index = 0;

    function typeWriter() {
      if (index < text.length) {
        document.getElementById("typewriter").innerHTML += text.charAt(index);
        index++;
        setTimeout(typeWriter, speed);
      }
    }

    // 调用打字函数
    typeWriter();
  </script>

</body>
</html>

解释

typeWriter 函数:通过 setTimeout 来递归调用自身,从而实现逐字显示效果。每次显示一个字符,并将其添加到 HTML 元素中。

speed 变量:用于控制文字打字的速度,单位为毫秒(可以根据需要调整)。

CSS 动画:为打字效果添加了光标闪烁效果,模拟了打字机效果,使用 @keyframes 来改变光标的显示与隐藏。

方法二:使用 CSS3 的 animation

html
<html>
    <head>
    <meta charset="UTF-8">
    <title>简单实现打字效果</title>
    </head>
    
    <style type="text/css">
    #type{
    
            width:300px;	/*这里修改文字长度*/
            white-space:nowrap;
            overflow:hidden;
            -webkit-animation: dy 3s steps(60, end) infinite;
            animation: dy 3s steps(50, end) infinite;
        }
        @-webkit-keyframes dy{
            from { width: 0;}
        }
        @keyframes dy{
            from { width: 0;}
        }
    </style>
    
    <body>
    <p id="type">测试测试</p>
    </body>
</html>

优缺点

优点:简单,代码量少,兼容性良好。

缺点:不能控制打字速度,只能按照系统默认速度打字。显示效果不够好。

方法三:使用 Typed.js 库

Typed.js 是一个专门用于打字效果的库,功能强大且简单易用。该工具库也支持vue。

官网地址 https://mattboldt.github.io/typed.js/

html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Typed.js 自动打字效果</title>
  <script src="https://cdn.jsdelivr.net/npm/typed.js@2.0.12"></script>
</head>
<body>

  <div id="typed-output"></div>

  <script>
    var options = {
      strings: ["这是一个自动打字效果的示例。", "它可以逐字打出你想要的文字。"],
      typeSpeed: 50,  // 打字速度
    //   backSpeed: 30,  // 删除速度
      loop: false,      // 是否循环播放
      showCursor: false // 是否显示光标
    };

    var typed = new Typed("#typed-output", options);
  </script>

</body>
</html>

注意事项

如果上述#typed-output里有文本, 会出现文本闪烁现象, 可以先清除文本, 在添加new Typed("#typed-output", options);

粤ICP备20009776号