如何将Js代码封装成Jquery插件

很多相同的Jquery代码会在很多页面使用,每次都复制粘贴太麻烦了,不如封装成一个Jquery插件就方便了,至于影响网页的速度不,我就没有测试了哈。

代码如下

这是一个自定闪烁打印文字的Jquery特效

HTML代码如下:

复制代码
<div id="code">
  <p>/**</p>
  <p>*2014-2-12</p>
  <p>*代码自动闪烁输入</p>
  <p>*/</p>
  2014-2-14,I want to say:<br />
  Baby, I love you forever!<br />
</div>
复制代码

Js代码:

复制代码
function typewriter(id){
  var $ele = document.getElementById(id);
  var str = $ele.innerHTML, progress = 0;
  $ele.innerHTML = '';
  var timer = setInterval(function() {
    var current = str.substr(progress, 1);
    if (current == '<') {
      progress = str.indexOf('>', progress) + 1;
    } else {
      progress++;
    }
    $ele.innerHTML =str.substring(0, progress) + (progress & 1 ? '_' : '');
    if (progress >= str.length) {
      clearInterval(timer);
    }
  }, 75);
}
复制代码

调用方法:

<script type="text/javascript">
        $(function () {
            typewriter("code");
        });
    </script>

下面开始对js代码进行Jquery插件封装了

复制代码
(function ($) {
    $.fn.typewriter = function () {
        var $ele = $(this), str = $ele.html(), progress = 0;
        $ele.html('');
        var timer = setInterval(function () {
            var current = str.substr(progress, 1);
            if (current == '<') {
                progress = str.indexOf('>', progress) + 1;
            } else {
                progress++;
            }
            $ele.html(str.substring(0, progress) + (progress & 1 ? '_' : ''));
            if (progress >= str.length) {
                clearInterval(timer);
            }
        }, 75);
    };
})(jQuery);
复制代码

调用方法:

<script type="text/javascript">
        $(function () {
            $("#code").typewriter();
        });
    </script>

封装完毕!

原文地址:https://www.cnblogs.com/jimmy1293/p/6703853.html