废话不多说,上代码~~

<!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 = '用JS实现动态打字效果'

  function typing () {
    if (i <= str.length) {
      divTyping.innerHTML = str.slice(0, i++) + '_'
      timer = setTimeout(typing, 200)
    }
    else {
      divTyping.innerHTML = str//结束打字,移除 _ 光标
      clearTimeout(timer)
    }
  }

  typing()
</script>
</html>

陌小江
7 声望1 粉丝