首页 > Web开发 > 详细

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

时间:2017-04-13 15:29:28      阅读:274      评论:0      收藏:0      [点我收藏+]

代码如下

这是一个自定闪烁打印文字的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>

封装完毕!

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

原文:http://www.cnblogs.com/jimmy1293/p/6703853.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!