欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

純js實(shí)現(xiàn)打字機(jī)效果

 更新時(shí)間:2021年10月28日 09:54:33   作者:帝尊菜鳥(niǎo)  
這篇文章主要為大家詳細(xì)介紹了純js實(shí)現(xiàn)打字機(jī)效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了js實(shí)現(xiàn)打字機(jī)效果的具體代碼,供大家參考,具體內(nèi)容如下

效果圖

應(yīng)用場(chǎng)景

用處不大,只是看到網(wǎng)上有類似的效果,寫(xiě)了四五十行看不懂的代碼,于是嘗試能不能簡(jiǎn)單的實(shí)現(xiàn)

html

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

        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;
  }
  
  @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="animate">|</span>');
 
   setTimeout(function() {
    index++;
 
    if(index === len + 1) {
     $('.animate').addClass('on');
     return;
    }
 
    input();
 
   }, Math.random() * 600)
 
   console.log(index);
  }
 
  input();

實(shí)現(xiàn)原理

通過(guò)定時(shí)器結(jié)合字符串截取實(shí)現(xiàn)類似于打字機(jī)的頓挫感,并通過(guò)遞歸累加index。相當(dāng)于第1s時(shí),截取一個(gè)字節(jié),第二秒時(shí),截取兩個(gè)字節(jié),以此類推……定時(shí)器時(shí)間取隨機(jī)數(shù),模擬打字的停頓感更好。遞歸調(diào)用中加結(jié)束循環(huán)條件,結(jié)束之前啟動(dòng)動(dòng)畫(huà),模擬光標(biāo)的跳動(dòng)。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論