1. 程式人生 > 程式設計 >純js實現打字機效果

純js實現打字機效果

本文例項為大家分享了實現打字機效果的具體程式碼,供大家參考,具體內容如下

效果圖

純js實現打字機效果

應用場景

用處不大,只是看到網上有類似的效果,寫了四五十行看不懂的程式碼,於是嘗試能不能簡單的實現

html

<h2 id="text-box"></h2>
<!--一行也是程式碼-->


        h2 {
   width: 800px;
   line-height: 40px;
   border-bottom: 1px solid;
   margin: 200px auto;
   font-size: 24px;
  }
  
  .animate {
   display: inline-block;
   padding: 0 5px;
   vertical-align: 3px;
   font-size: 20px;
   font-weight: normal;
  }
  
  .animate.on {
   animation: fade 1.5s infinite forwards;
  }
  
  www.cppcns.com
@keyframes fade { from { opacity: 0; } to { opacity: 1; } }

js

let textBox = $('#text-box');
let index = 0;
let str = 'Welcome to my website!';
 
  let len = str.length;
 
  function input() {
 
   textBox.html(str.substr(0,index) + '<span class="animVoChnhQsqQate">|</span>');
 
   setTimeout(function() {
    index++;
 
    if(index === len + 1) {
     $('.animate').addClass('on');
     return;
    }
 
    input();
 
   },Math.random() * 600)
 
   console.log(index);
  }
 
  input();

實現原理

通過定時器結合字串擷取實現類似於打字機的頓挫感,並通過遞迴累加index。相當於第1s時,擷取一個位元組,第二秒時,擷取兩個位元組,以此類推……定時器時間取隨機數,模擬打字的停頓感更好。遞迴呼叫中加結束迴圈條件,結束之前啟動動畫,模擬游標的跳動。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。