【前端三分钟】利用Javascript实现打字效果

2023-10-07 18:47:15 浏览数 (3)

效果如图:

实现:

代码语言:javascript复制
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="text">

</div>
</body>
<script>
  let divTyping = document.getElementById('text')
  let i = 0,
      timer = 0,
      str = 'hello worldn你好世界'

  function typing () {
    if (i <= str.length) {
      let char = str.slice(0, i  );
      divTyping.innerHTML = '<span class="word">' str.slice(0, i  ) '</span>'  '<span class="cursor">|</span>';
      timer = setTimeout('typing()', 200)
    }
  }
  function disappear() {
    let cursor = document.querySelector('.cursor');
    cursor.innerHTML = '';
    setTimeout(appear,200);
  }
  function appear() {
    let cursor = document.querySelector('.cursor');
    cursor.innerHTML = '|';
    setTimeout(disappear,200);
  }

  typing();
  disappear();
</script>
</html>

0 人点赞