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

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

(0)

相关推荐

  • JS实现的打字机效果完整实例

    本文实例讲述了JS实现的打字机效果.分享给大家供大家参考,具体如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame Remove this if you use the

  • JS实现的自动打字效果示例

    本文实例讲述了JS实现的自动打字效果.分享给大家供大家参考,具体如下: <!DOCTYPE html> <html> <head> <meta charset='utf-8'> <title>js typing</title> </head> <body> <div id='divTyping'></div> <script> var str = 'js 实现的 打字效果,感

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

    方法一(纯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

  • 使用纯JS代码判断字符串中有多少汉字的实现方法(超简单实用)

    在网站开发中,经常会简单使用js代码来判断字符串中有多少汉字的功能.今天小编抽时间给大家分享实现代码.废话不多说了,直接给大家贴代码了. $("form").submit(function () { var content = editor.getContentTxt(); var sum = 0; re = /[\u4E00-\u9FA5]/g; //测试中文字符的正则 if (content) { if (re.test(content)) //使用正则判断是否存在中文 { if

  • js获取html的span标签的值方法(超简单)

    HTML中代码为: <span id="testid">aaaa</span> 获取的js代码: 方法一:.innerText var x1 = document.getElementById("testid").innerText; alert("x1="+x1); 方法二:.innerHTML var x2 = document.getElementById("testid").innerHTML;

  • 原生js实现ajax方法(超简单)

    上一篇文章写到原生js取代jquery的一些常用函数:原生js仿jquery一些常用方法,那么,ajax如何实现呢?如下是一个比较完整的ajax() function ajax(){ var ajaxData = { type:arguments[0].type || "GET", url:arguments[0].url || "", async:arguments[0].async || "true", data:arguments[0].d

  • js判断checkbox是否选中个数的方法(超简单)

    实例如下: <SCRIPT LANGUAGE="JavaScript"> //判断同类型 function checkboxnum(){ var form = document.forms['formbj1']; var i,j=0; for (i=0; i<form.length; i++){ var e=form[i]; if (e.checked && e.type=='checkbox' && e.name=='bjid[]')

  • python下载图片实现方法(超简单)

    如下所示: import urllib.request response = urllib.request.urlopen('http://www.jb51.net/g/500/600') cat_img = response.read() with open('cat_500_600.jpg','wb') as f: f.write(cat_img) urlopen()括号里既可以是一个字符串也可以是一个request对象,当传入字符串的时候会转换成一个request对象,因此代码 respo

  • Asp.NET控制文件上传的大小方法(超简单)

    在web.config中的system.web 节点下添加如下代码: 第2行的maxRequestLength="8192",这里限制最大为8MB,可以自行设置.executionTimeout="800",executionTimeout预设(即默认)是 90 秒 <system.web> <httpRuntime maxRequestLength="8192" executionTimeout="800"

  • Android studio 3.0 查看手机文件系统的方法(超简单)

    众所周知,我们要查看安卓手机中文件系统前提条件是要root手机,然后去DDMS里面去看,但是现在很多手机都不好root,替代的方法是用电脑模拟器,不管怎么样,都挺麻烦的,最近更新Android studio 到3.0版本,无意间发现了一个方法,非常简单,还不用root手机. 1.手机USB线连接手机,打开调试模式 2.打开AS,找到窗口右下角的Device File Explorer,如下图: 3.点击这个按钮,就直接打开了手机的文件系统,如图: 4.接下来看下我们最关注的data/data和s

  • MAC中显示隐藏文件和不显示隐藏文件的方法(超简单)

    MAC中显示隐藏文件有很多种方法,最简单的是通过在Mac终端输入命令. 显示隐藏文件(注意空格和大小写): defaults write com.apple.finder AppleShowAllFiles -bool true 或 defaults write com.apple.finder AppleShowAllFiles YES 不显示隐藏文件: defaults write com.apple.finder AppleShowAllFiles -bool false 或 defaul

  • Ubuntu系统安装使用搜狗输入法的方法(超简单)

    Ubuntu自带的中文输入法不得不说真是辣鸡啊,怎么也用不明白. 推荐使用搜狗输入法 默认输入法框架 IBus 搜狗输入法->fcitx输入法框架->先添加软件源,可在软件中心->fcitx->添加源 具体安装步骤如下: 1.安装fcitx libssh2-1      $sudo apt-get install fcitx libssh2-1 2.下载deb包                    搜狗输入法forLinux 3.安装                       

随机推荐