打字效果动画的4种实现方法(超简单)


Posted in Javascript onOctober 18, 2017

方法一(纯css实现):

html代码:

<h1 class="typing typing-item">打字动画打字动画打字动画</h1>

css样式:

.typing{
 font-size: 1rem;
 padding-top: 6%;
 margin-bottom: 5%;
 font-weight: normal;
 letter-spacing: .3rem;
 -webkit-animation: type 2s steps(50, end) forwards;
 animation: type 2s steps(50, end) forwards;
}
.typing-item{
 text-align: center;
 color: black;
 width:100%;
 white-space:nowrap;
 overflow:hidden;
}
@-webkit-keyframes type{
 from { width: 0;}
}

@keyframes type{
 from { width: 0;}
}

缺点:只能实现一行式的打字效果,无法打出一段落文字

方法二(jquery):

html代码:

<div class="text-container">
 <span class="text-static"></span>
 <span class="text"></span>
 <span class="cursor">|</span>
</div>

jquery代码:

<script type="text/javascript" src="../js/jquery.js"></script>
<script>
  $(function() {
   myPrint(["hello my word!"], 100);

   function myPrint(arr, speed) {
    var index = 0;
    var str = arr[index];
    var i = 0;
    var add = true;
    var mySetInterval = setInterval(function() {
     // 延时4个字符的时间
     if (i == str.length + 4) {
      add = false;
      // 如果是最后一个字符串则终止循环函数
      if (index + 1 >= arr.length) {
       clearInterval(mySetInterval);
      }
     } else if (i == -2) {
      // 删除后延时2个字符的时间
      add = true;
      str = arr[++index];
     }
     setTimeout(function() {
      if (add) {
       i++;
       $(".text").html(str.substring(0, i));
      } else {
       $(".text").html(str.substring(0, i - 1));
       i--;
      }
     })

    }, speed)
   }

  })
 </script>

方法三(jquery-typed插件):

html代码:

<div class="content">
 <div class="content-div">
  <span id="content-item"></span>
 </div>
</div>
<input type="hidden" id="content" value="内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容" />

引入Typed.js,Typed.js内容如下

// The MIT License (MIT)

// Typed.js | Copyright (c) 2014 Matt Boldt | www.mattboldt.com

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.




! function($) {

 "use strict";

 var Typed = function(el, options) {

  // chosen element to manipulate text
  this.el = $(el);

  // options
  this.options = $.extend({}, $.fn.typed.defaults, options);

  // attribute to type into
  this.isInput = this.el.is('input');
  this.attr = this.options.attr;

  // show cursor
  this.showCursor = this.isInput ? false : this.options.showCursor;

  // text content of element
  this.elContent = this.attr ? this.el.attr(this.attr) : this.el.text()

  // html or plain text
  this.contentType = this.options.contentType;

  // typing speed
  this.typeSpeed = this.options.typeSpeed;

  // add a delay before typing starts
  this.startDelay = this.options.startDelay;

  // backspacing speed
  this.backSpeed = this.options.backSpeed;

  // amount of time to wait before backspacing
  this.backDelay = this.options.backDelay;

  // input strings of text
  this.strings = this.options.strings;

  // character number position of current string
  this.strPos = 0;

  // current array position
  this.arrayPos = 0;

  // number to stop backspacing on.
  // default 0, can change depending on how many chars
  // you want to remove at the time
  this.stopNum = 0;

  // Looping logic
  this.loop = this.options.loop;
  this.loopCount = this.options.loopCount;
  this.curLoop = 0;

  // for stopping
  this.stop = false;

  // custom cursor
  this.cursorChar = this.options.cursorChar;

  // shuffle the strings
  this.shuffle = this.options.shuffle;
  // the order of strings
  this.sequence = [];

  // All systems go!
  this.build();
 };

 Typed.prototype = {

  constructor: Typed

  ,
  init: function() {
   // begin the loop w/ first current string (global self.string)
   // current string will be passed as an argument each time after this
   var self = this;
   self.timeout = setTimeout(function() {
    for (var i=0;i<self.strings.length;++i) self.sequence[i]=i;

    // shuffle the array if true
    if(self.shuffle) self.sequence = self.shuffleArray(self.sequence);

    // Start typing
    self.typewrite(self.strings[self.sequence[self.arrayPos]], self.strPos);
   }, self.startDelay);
  }

  ,
  build: function() {
   // Insert cursor
   if (this.showCursor === true) {
    this.cursor = $("<span class=\"typed-cursor\">" + this.cursorChar + "</span>");
    this.el.after(this.cursor);
   }
   this.init();
  }

  // pass current string state to each function, types 1 char per call
  ,
  typewrite: function(curString, curStrPos) {
   // exit when stopped
   if (this.stop === true) {
    return;
   }

   // varying values for setTimeout during typing
   // can't be global since number changes each time loop is executed
   var humanize = Math.round(Math.random() * (100 - 30)) + this.typeSpeed;
   var self = this;

   // ------------- optional ------------- //
   // backpaces a certain string faster
   // ------------------------------------ //
   // if (self.arrayPos == 1){
   // self.backDelay = 50;
   // }
   // else{ self.backDelay = 500; }

   // contain typing function in a timeout humanize'd delay
   self.timeout = setTimeout(function() {
    // check for an escape character before a pause value
    // format: \^\d+ .. eg: ^1000 .. should be able to print the ^ too using ^^
    // single ^ are removed from string
    var charPause = 0;
    var substr = curString.substr(curStrPos);
    if (substr.charAt(0) === '^') {
     var skip = 1; // skip atleast 1
     if (/^\^\d+/.test(substr)) {
      substr = /\d+/.exec(substr)[0];
      skip += substr.length;
      charPause = parseInt(substr);
     }

     // strip out the escape character and pause value so they're not printed
     curString = curString.substring(0, curStrPos) + curString.substring(curStrPos + skip);
    }

    if (self.contentType === 'html') {
     // skip over html tags while typing
     var curChar = curString.substr(curStrPos).charAt(0)
     if (curChar === '<' || curChar === '&') {
      var tag = '';
      var endTag = '';
      if (curChar === '<') {
       endTag = '>'
      } else {
       endTag = ';'
      }
      while (curString.substr(curStrPos).charAt(0) !== endTag) {
       tag += curString.substr(curStrPos).charAt(0);
       curStrPos++;
      }
      curStrPos++;
      tag += endTag;
     }
    }

    // timeout for any pause after a character
    self.timeout = setTimeout(function() {
     if (curStrPos === curString.length) {
      // fires callback function
      self.options.onStringTyped(self.arrayPos);

      // is this the final string
      if (self.arrayPos === self.strings.length - 1) {
       // animation that occurs on the last typed string
       self.options.callback();

       self.curLoop++;

       // quit if we wont loop back
       if (self.loop === false || self.curLoop === self.loopCount)
        return;
      }

      self.timeout = setTimeout(function() {
       self.backspace(curString, curStrPos);
      }, self.backDelay);
     } else {

      /* call before functions if applicable */
      if (curStrPos === 0)
       self.options.preStringTyped(self.arrayPos);

      // start typing each new char into existing string
      // curString: arg, self.el.html: original text inside element
      var nextString = curString.substr(0, curStrPos + 1);
      if (self.attr) {
       self.el.attr(self.attr, nextString);
      } else {
       if (self.isInput) {
        self.el.val(nextString);
       } else if (self.contentType === 'html') {
        self.el.html(nextString);
       } else {
        self.el.text(nextString);
       }
      }

      // add characters one by one
      curStrPos++;
      // loop the function
      self.typewrite(curString, curStrPos);
     }
     // end of character pause
    }, charPause);

    // humanized value for typing
   }, humanize);

  }

  ,
  backspace: function(curString, curStrPos) {
   // exit when stopped
   if (this.stop === true) {
    return;
   }

   // varying values for setTimeout during typing
   // can't be global since number changes each time loop is executed
   var humanize = Math.round(Math.random() * (100 - 30)) + this.backSpeed;
   var self = this;

   self.timeout = setTimeout(function() {

    // ----- this part is optional ----- //
    // check string array position
    // on the first string, only delete one word
    // the stopNum actually represents the amount of chars to
    // keep in the current string. In my case it's 14.
    // if (self.arrayPos == 1){
    // self.stopNum = 14;
    // }
    //every other time, delete the whole typed string
    // else{
    // self.stopNum = 0;
    // }

    if (self.contentType === 'html') {
     // skip over html tags while backspacing
     if (curString.substr(curStrPos).charAt(0) === '>') {
      var tag = '';
      while (curString.substr(curStrPos).charAt(0) !== '<') {
       tag -= curString.substr(curStrPos).charAt(0);
       curStrPos--;
      }
      curStrPos--;
      tag += '<';
     }
    }

    // ----- continue important stuff ----- //
    // replace text with base text + typed characters
    var nextString = curString.substr(0, curStrPos);
    if (self.attr) {
     self.el.attr(self.attr, nextString);
    } else {
     if (self.isInput) {
      self.el.val(nextString);
     } else if (self.contentType === 'html') {
      self.el.html(nextString);
     } else {
      self.el.text(nextString);
     }
    }

    // if the number (id of character in current string) is
    // less than the stop number, keep going
    if (curStrPos > self.stopNum) {
     // subtract characters one by one
     curStrPos--;
     // loop the function
     self.backspace(curString, curStrPos);
    }
    // if the stop number has been reached, increase
    // array position to next string
    else if (curStrPos <= self.stopNum) {
     self.arrayPos++;

     if (self.arrayPos === self.strings.length) {
      self.arrayPos = 0;

      // Shuffle sequence again
      if(self.shuffle) self.sequence = self.shuffleArray(self.sequence);

      self.init();
     } else
      self.typewrite(self.strings[self.sequence[self.arrayPos]], curStrPos);
    }

    // humanized value for typing
   }, humanize);

  }
  /**
   * Shuffles the numbers in the given array.
   * @param {Array} array
   * @returns {Array}
   */
  ,shuffleArray: function(array) {
   var tmp, current, top = array.length;
   if(top) while(--top) {
    current = Math.floor(Math.random() * (top + 1));
    tmp = array[current];
    array[current] = array[top];
    array[top] = tmp;
   }
   return array;
  }

  // Start & Stop currently not working

  // , stop: function() {
  //  var self = this;

  //  self.stop = true;
  //  clearInterval(self.timeout);
  // }

  // , start: function() {
  //  var self = this;
  //  if(self.stop === false)
  //  return;

  //  this.stop = false;
  //  this.init();
  // }

  // Reset and rebuild the element
  ,
  reset: function() {
   var self = this;
   clearInterval(self.timeout);
   var id = this.el.attr('id');
   this.el.after('<span id="' + id + '"/>')
   this.el.remove();
   if (typeof this.cursor !== 'undefined') {
    this.cursor.remove();
   }
   // Send the callback
   self.options.resetCallback();
  }

 };

 $.fn.typed = function(option) {
  return this.each(function() {
   var $this = $(this),
    data = $this.data('typed'),
    options = typeof option == 'object' && option;
   if (!data) $this.data('typed', (data = new Typed(this, options)));
   if (typeof option == 'string') data[option]();
  });
 };

 $.fn.typed.defaults = {
  strings: ["These are the default values...", "You know what you should do?", "Use your own!", "Have a great day!"],
  // typing speed
  typeSpeed: 0,
  // time before typing starts
  startDelay: 0,
  // backspacing speed
  backSpeed: 0,
  // shuffle the strings
  shuffle: false,
  // time before backspacing
  backDelay: 500,
  // loop
  loop: false,
  // false = infinite
  loopCount: false,
  // show cursor
  showCursor: true,
  // character for cursor
  cursorChar: "|",
  // attribute to type (null == text)
  attr: null,
  // either html or text
  contentType: 'html',
  // call when done callback function
  callback: function() {},
  // starting callback function before each string
  preStringTyped: function() {},
  //callback for every typed string
  onStringTyped: function() {},
  // callback for reset
  resetCallback: function() {}
 };


}(window.jQuery);

调用Typed.js

var string = $('#content').val();
$('#content-item').typed({
 strings: ["" + string],
 typeSpeed: 50,
 backDelay: 800,
 loop: false,
 loopCount: false
});

方法四(纯js):

html代码:

<div id="typing"></div>

js代码:

<script>
 var str = '内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容内容';
 var i = 0;
 function typing(){
  var divTyping = document.getElementById('typing');
  if (i <= str.length) {
   divTyping.innerHTML = str.slice(0, i++) + '_';
   setTimeout('typing()', 200);
  }
  else{
   divTyping.innerHTML = str;
  }
 }
 typing();
</script>

最后,发现实现打字效果还是蛮简单的对吧,css的思路是利用width和overflow:hidden,动画让宽度变宽实现像打字的样式,但是样式有限,不能实现多行显示。js/jquery,普遍都是先得到字的内容,然后再逐字往容器中添加文字。问题不难,主要是要善于思考!!

以上这篇打字效果动画的4种实现方法(超简单)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
JS控制表格隔行变色
Jun 26 Javascript
为jQuery增加join方法的实现代码
Nov 28 Javascript
基于jQuery实现放大镜特效
Oct 19 Javascript
jQuery对象的链式操作用法分析
May 10 Javascript
JS图片放大效果简单实现代码
Sep 08 Javascript
浅谈JS之iframe中的窗口
Sep 13 Javascript
使用纯JS代码判断字符串中有多少汉字的实现方法(超简单实用)
Nov 12 Javascript
JS匿名函数实例分析
Nov 26 Javascript
JavaScript实现数组降维详解
Jan 05 Javascript
js判断文件类型大小并给出提示的实现方法
Jan 03 Javascript
从Node.js事件触发器到Vue自定义事件的深入讲解
Jun 26 Javascript
vue实现给div绑定keyup的enter事件
Jul 31 Javascript
Angularjs 手写日历的实现代码(不用插件)
Oct 18 #Javascript
基于JavaScript表单脚本(详解)
Oct 18 #Javascript
VUE饿了么树形控件添加增删改功能的示例代码
Oct 17 #Javascript
vue-router实现tab标签页(单页面)详解
Oct 17 #Javascript
BACKBONE.JS 简单入门范例
Oct 17 #Javascript
JS获取一个表单字段中多条数据并转化为json格式
Oct 17 #Javascript
JS解决position:sticky的兼容性问题的方法
Oct 17 #Javascript
You might like
php中随机显示图片的函数代码
2011/06/23 PHP
Javascript与PHP验证用户输入URL地址是否正确
2014/10/09 PHP
php中file_exists函数使用详解
2015/05/08 PHP
[原创]PHP实现逐行删除文件右侧空格的方法
2015/12/25 PHP
PHP中Trait及其应用详解
2017/02/14 PHP
js 禁止选择功能实现代码(兼容IE/Firefox)
2010/04/23 Javascript
jquery动态添加删除div 具体实现
2013/07/20 Javascript
输入自动提示搜索提示功能的javascript:sugggestion.js
2013/09/02 Javascript
jquery删除数据记录时的弹出提示效果
2014/05/06 Javascript
JavaScript弹出新窗口后向父窗口输出内容的方法
2015/04/06 Javascript
使用jQuery或者原生js实现鼠标滚动加载页面新数据
2016/03/06 Javascript
搞定immutable.js详细说明
2016/05/02 Javascript
js 自带的sort() 方法全面了解
2016/08/16 Javascript
基于vue2.0+vuex+localStorage开发的本地记事本示例
2017/02/28 Javascript
JS实现的JSON数组去重算法示例
2018/04/11 Javascript
使用vue-cli导入Element UI组件的方法
2018/05/16 Javascript
JavaScript循环遍历你会用哪些之小结篇
2018/09/28 Javascript
Node.js API详解之 console模块用法详解
2020/05/12 Javascript
解决Vue的文本编辑器 vue-quill-editor 小图标样式排布错乱问题
2020/08/03 Javascript
微信小程序实现弹幕墙(祝福墙)
2020/11/18 Javascript
[02:32]DOTA2英雄基础教程 美杜莎
2014/01/07 DOTA
Python实现把回车符\r\n转换成\n
2015/04/23 Python
初学python的操作难点总结(新手必看篇)
2017/08/03 Python
python实现祝福弹窗效果
2019/04/07 Python
Python3网络爬虫开发实战之极验滑动验证码的识别
2019/08/02 Python
Python安装及Pycharm安装使用教程图解
2019/09/20 Python
解析Python3中的Import
2019/10/13 Python
python交互模式基础知识点学习
2020/06/18 Python
The Hut英国:英国领先的豪华在线百货商店
2019/07/26 全球购物
自考毕业自我鉴定范文
2013/10/27 职场文书
精彩的演讲稿开头
2014/05/08 职场文书
小学语文的各类谚语(70首)
2019/08/15 职场文书
Python Django ORM连表正反操作技巧
2021/06/13 Python
JavaScript 数组去重详解
2021/09/15 Javascript
vue 给数组添加新对象并赋值
2022/04/20 Vue.js
Win10本地连接不见了怎么恢复? win10系统电脑本地连接不见了解决方法
2023/01/09 数码科技