当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 打字效果动画的4种实现方法(超简单)

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

方法一(纯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种实现方法(超简单)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网