js:使用typed.js实现打字动画效果

效果预览
在这里插入图片描述

实现方式一: 原生JS实现

<div id="code">
我感到未尝经验的无聊,是自此以后的事。我当初是不知其所以然的;
后来想,凡有一人的主张,得了赞和,是促其前进的,得了反对,是促其奋斗的,独有叫喊于生人中,
而生人并无反应,既非赞同,也无反对,如置身毫无边际的荒原,无可措手的了,这是怎样的悲哀呵,
我于是以我所感到者为寂寞。这寂寞又一天一天地长大起来,如大毒蛇,缠住了我的灵魂了。
</div>

<script>
  Element.prototype.typewriter = function (a) {
      
      
    var d = this,
      c = d.innerHTML,
      b = 0
    d.innerHTML = ''
    var e = setInterval(function () {
      
      
      b++
      d.innerHTML = c.substring(0, b) + (b & 1 ? '|' : '') //&1 这个表达式 可以用来 判断 a的奇偶性
      if (b >= c.length) {
      
      
        clearInterval(e)
      }
    }, 150)
    return this
  }
  document.getElementById('code').typewriter()
</script>

实现方式二:typed.js实现

A JavaScript Typing Animation Library

译文:JavaScript打字动画库

相关资料

使用示例

1、CDN

  <!-- Element to contain animated typing -->
  <span id="element"></span>

  <!-- Load library from the CDN -->
  <script src="https://unpkg.com/[email protected]/dist/typed.umd.js"></script>

  <!-- Setup and start animation! -->
  <script>
    var typed = new Typed('#element', {
      
      
      strings: ['<i>First</i> sentence.', '&amp; a second sentence.'],
      typeSpeed: 50,
    });
  </script>

2、ESM

安装

npm install typed.js

示例

import Typed from 'typed.js';

const typed = new Typed('#element', {
    
    
  strings: ['<i>First</i> sentence.', '&amp; a second sentence.'],
  typeSpeed: 50,
});

参考资料

  1. JS实现打字效果

猜你喜欢

转载自blog.csdn.net/mouday/article/details/131538274
今日推荐