如何用 JavaScript 建立一個打字效果?


要使用 JavaScript 建立一個打字效果,以下是程式碼 -

範例

 實戰演示

<!DOCTYPE html>
<html>
<head>
<style>
   body{
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
   }
   button{
      padding:10px;
      font-size: 18px;
      background-color: rgb(128, 19, 218);
      color:white;
      border:none;
   }
   .heading{
      color:crimson;
   }
</style>
</head>
<body>
<h1>typeText</h1>
<button class="typeButton">Click me</button>
<h2 class="heading"></h2>
<script>
   document.querySelector('.typeButton').addEventListener('click',typeText);
   var i = 0;
   var text = 'This text is currently being typed across... It is still typing..';
   var speed = 50;
   function typeText() {
      if (i < text.length) {
         document.querySelector('.heading').innerHTML += text.charAt(i);
         i++;
         setTimeout(typeText, speed);
      }
   }
</script>
</body>
</html>

輸出

以上程式碼將產生以下輸出 -

點選“點選我”按鈕後 -

更新日期: 12-May-2020

213 次觀看

開啟您的事業

完成課程以獲得認證

開始學習
廣告