JavaScript模拟实现键盘打字效果

<div class="jb51code">
<pre class="brush:js;">
$(function () {

  var input_type = {
    init:function ($obj) {
      this.name = $obj.html().split("")
      this.length = this.name.length;
      this.i = 0;
    },pri:function () {
      var $this = this
      //在此处只能使用闭包,因为windown.settimeout使函数的this指向object windown,而非原型链的this对象。而此时我需要递归,所以只能将this对象传到闭包内,递归匿名的闭包函数。
      return (function () {
        if ($this.i > $this.length) {
          window.clearTimeout(Go)
          return false;
        }
        var char = $this.name
        $(".div1").append(char[$this.i])
        $this.i++
        var Go = window.setTimeout(arguments.callee,100)//<a href="https://www.jb51.cc/tag/zaizheli/" target="_blank" class="keywords">在这里</a>arguments.callee妙用因为是匿名闭包,<a href="https://www.jb51.cc/tag/diaoyong/" target="_blank" class="keywords">调用</a><a href="https://www.jb51.cc/tag/hanshu/" target="_blank" class="keywords">函数</a>本身。
      })
    }
  }

//建立class类
function Input_type() {
this.init.apply(this,arguments)
}

  Input_type.prototype = input_type

//创建实例
var p = new Input_type($(".content"))
p.pri()()

});</pre>

总结:为了实现每次循环间隔时间,用window.settimeout递归的写法。 因为想用原型链封装,this冲突,所以递归调用匿名的闭包函数。用arguments.callee表示匿名函数

HTML代码

rush:js;">

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...