实现ChatGPT的文字输出效果

原文发表于zhu's Blog

      阿猪是计算机业余爱好者,把网页做得美观高大上对阿猪是一种折磨和挑战,所以阿猪做出来的网页都是清一色的word文档风格。为了给low逼的网页提升点儿逼格,阿猪决定模仿一下ChatGPT的文字输出效果。

      先上效果图::

      以下是完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ChatGPT Typing Effect</title>
  <style>
    #output {
      display: inline;
    }

    .cursor {
      display: inline-block;
      width: 10px;
      height: 20px;
      background-color: black;
      vertical-align: text-bottom;
      animation: blink 1s infinite;
    }

    @keyframes blink {
      50% {
        opacity: 0;
      }
    }
  </style>
</head>
<body>
  <h1>ChatGPT Typing Effect</h1>
  <div id="output"></div><span class="cursor" id="cursor"></span>
  <div id="givenText" style="display: none;">
    <strong>加粗文本-Bold Text</strong><br>
    <em>斜体文本-Italic Text</em><br>
    <u>下划线文本-Underline Text</u><br>
    <span style="color: red;">红色文本-Red Text</span><br>
    <span style="font-size: 24px;">大字体文本-Large Text</span><br>
    <a href="https://github.com/azhu021/">链接示例-Link Example</a>
  </div>

  <script>
    const outputElement = document.getElementById("output");
    const cursorElement = document.getElementById("cursor");
    const givenTextElement = document.getElementById("givenText");
    const givenText = givenTextElement.innerHTML;
    let currentIndex = 0;
    let currentHTML = "";

    function typeText() {
      if (currentIndex < givenText.length) {
        const currentChar = givenText.charAt(currentIndex);

        if (currentChar === "<") {
          const closingTagIndex = givenText.indexOf(">", currentIndex);
          currentHTML += givenText.slice(currentIndex, closingTagIndex + 1);
          currentIndex = closingTagIndex + 1;
        } else {
          currentHTML += currentChar;
          currentIndex++;
        }

        outputElement.innerHTML = currentHTML;
        setTimeout(typeText, 100); // 设置打字速度,单位为毫秒
      } else {
        // 当打印完成时,移除光标的闪烁效果
        cursorElement.classList.remove("cursor");
      }
    }

    typeText();
  </script>
</body>
</html>

      这段代码中:

(1)`<div id="output"></div>`用于显示输出文本内容。

(2)`<span class="cursor" id="cursor"></span>`用于显示闪烁的光标。

(3)`<style></style>`中通过CSS控制光标闪烁的效果。

(4)`<script></script>`中通过javascript控制文字的输出。

(5)`<div id="givenText" style="display: none;">`中的内容不会显示,只用于向javascript中的givenTextElement变量赋值。

(6)文字输出的效果是通过拆分`givenTextElement`变量中的内容向`currentHTML`变量传递,然后使用`innerHTML`方法以覆盖显示的方式不断输出显示。

(7)可以通过修改`setTimeout(typeText, 100)`来控制文字输出的速度。

(8)这段代码只是在实现了与ChatGPT相似的视觉效果,但是原理与ChatGPT并不相同。这段代码需要提前获取需要显示的全部文本内容,然后逐渐输出显示;而ChatGPT则使用了类似stream传输的技术,并不依赖于提前获取需要显示的全部文本内容。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值