2025年4月8日 星期二 乙巳(蛇)年 正月初九 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > JavaScript

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

时间:05-24来源:作者:点击数:53

效果预览

在这里插入图片描述

实现方式一: 原生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/typed.js@2.0.16/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,
  • });
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门