Html实现打字机效果

发布于 2023-12-26  383 次阅读


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    body {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100vh;
      margin: 0;
      background-color: #f4f4f4;
    }

    .typewriter-text {
	overflow: hidden;
	white-space: pre-line;
	font-size: 20px;
	border-right: 0.15em solid transparent; /* 初始时光标透明 */
    }
  </style>
</head>
<body>
  <div class="typewriter-text"></div>

  <script>
    // 如果要添加打字机效果的文本
    const texts = [
      "第一行",
      "第二行",
      "第三行"
    ];

    // 获取显示文本的元素
    const typewriterText = document.querySelector('.typewriter-text');

    let textIndex = 0;
    let charIndex = 0;

    function type() {
      if (textIndex < texts.length) {
        if (charIndex <= texts[textIndex].length) {
          typewriterText.innerHTML = texts[textIndex].substring(0, charIndex) + '<br>';
          charIndex++;
          setTimeout(type, 98); // 设置打字速度
        } else {
          // 打完一行后删除
          setTimeout(deleteText, 2000); // 设置删除延迟时间
        }
      } else {
        // 打完全部文本后展现
        setTimeout(showAllText, 500); // 设置展现延迟时间
      }
    }

    function deleteText() {
      if (charIndex >= 0) {
        typewriterText.innerHTML = texts[textIndex].substring(0, charIndex) + '<br>';
        charIndex--;
        setTimeout(deleteText, 45); // 设置删除速度
      } else {
        textIndex++;
        charIndex = 0;
        setTimeout(type, 500); // 设置下一行延迟时间
      }
    }

    function showAllText() {
      typewriterText.innerHTML = ''; // 清空内容
      displayAllText(0, 0); // 逐行逐字显示
    }

    function displayAllText(lineIndex, charIndex) {
      if (lineIndex < texts.length) {
        if (charIndex < texts[lineIndex].length) {
          typewriterText.innerHTML += texts[lineIndex][charIndex];
          charIndex++;
          setTimeout(() => displayAllText(lineIndex, charIndex), 100); // 设置打字速度
        } else {
          typewriterText.innerHTML += '<br>';
          displayAllText(lineIndex + 1, 0); // 逐行显示
        }
      }
    }

    // 开始打字
    type();
  </script>
</body>
</html>
最后更新于 2023-12-26