js打字机效果 纯js实现打字机效果

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

js打字机效果 纯js实现打字机效果

帝尊菜鸟   2021-10-28 我要评论
想了解纯js实现打字机效果的相关内容吗,帝尊菜鸟在本文为您仔细讲解js打字机效果的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:js,打字机,下面大家一起来学习吧。

效果图

应用场景

用处不大,只是看到网上有类似的效果,写了四五十行看不懂的代码,于是尝试能不能简单的实现

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();

实现原理

通过定时器结合字符串截取实现类似于打字机的顿挫感,并通过递归累加index。相当于第1s时,截取一个字节,第二秒时,截取两个字节,以此类推……定时器时间取随机数,模拟打字的停顿感更好。递归调用中加结束循环条件,结束之前启动动画,模拟光标的跳动。

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们