2020-11-18 原生js实现自动打字效果

原理

使用定时器,对要输出的文字进行遍历,每遍历一次,都增加一个字以及在段尾加上"|"暗示别人正在打字。

js代码

      const fangWrite = (theString, queryString, timeInterval, identifier) => {
        const thisString = theString || "";
        const thisQueryString = queryString || "body";
        const thisDOM = document.querySelectorAll(queryString)[0];
        const thisTimeInterval = timeInterval || 200;
        const thisIdentifier = identifier || "|";

        for (let index = 0, thisWrite = ""; index < theString.length; index++) {
          thisWrite = thisWrite + theString[index];
          const theTime = thisTimeInterval * index;
          setTimeout(
            (thisDOM, thisWrite, thisIdentifier) => {
              thisDOM.innerHTML = thisWrite + thisIdentifier;
            },
            theTime,
            thisDOM,
            thisWrite,
            thisIdentifier
          );
        }
        const theTime = thisTimeInterval * theString.length;
        setTimeout(() => {
          thisDOM.innerHTML = theString;
        }, theTime);
      };
      fangWrite("js 实现的 打字效果,感觉蛮有趣的。", "body", 200, "_");

页面代码:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>自动打字</title>
  </head>
  <body>
    <div id="divTyping"></div>
    <script>
      const fangWrite = (theString, queryString, timeInterval, identifier) => {
        const thisString = theString || "";
        const thisQueryString = queryString || "body";
        const thisDOM = document.querySelectorAll(queryString)[0];
        const thisTimeInterval = timeInterval || 200;
        const thisIdentifier = identifier || "|";

        for (let index = 0, thisWrite = ""; index < theString.length; index++) {
          thisWrite = thisWrite + theString[index];
          const theTime = thisTimeInterval * index;
          setTimeout(
            (thisDOM, thisWrite, thisIdentifier) => {
              thisDOM.innerHTML = thisWrite + thisIdentifier;
            },
            theTime,
            thisDOM,
            thisWrite,
            thisIdentifier
          );
        }
        const theTime = thisTimeInterval * theString.length;
        setTimeout(() => {
          thisDOM.innerHTML = theString;
        }, theTime);
      };
      fangWrite("js 实现的 打字效果,感觉蛮有趣的。", "#divTyping", 200, "_");
    </script>
  </body>
</html>

仿写来源:
JS实现的自动打字效果示例

posted @ 2020-11-18 09:51  方朝端  阅读(20)  评论(0编辑  收藏  举报

我的页脚HTML代码