Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

How to create a typing effect with JavaScript?


เพื่อสร้างเอฟเฟกต์การพิมพ์ (typing effect) ด้วย 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>

ผลลัพธ์

โค้ดข้างต้นจะสร้างผลลัพธ์ดังนี้ -

How to create a typing effect with JavaScript?

เมื่อคลิกปุ่ม "Click me" -

How to create a typing effect with JavaScript?