jQuery 插件开发实践

风行水上 @ 2014-05-07 15:30:41
标签:

    就本质而言,开发一个jQuery插件相当于扩展jQuery.fn对象。即:

    $.fn.hello_world = function(){
    }
    
    $('#hello').hello_world();
    

    插件实例

    下面是一个实际中的例子,用于伴随窗口滚动而自动调整飘浮栏的位置。很好的封装和实现了

    • 同时作用于多个实例
    • 用户参数的初始化和传递
    (function($){
      var pluginName = 'scrollfloat';
    
      var defaults = {
        latency:200,
        top:36
      };
    
      function Plugin(element, options){
        this.$that = $(element);
        this.options = $.extend({}, defaults, options);
        this.init();
      }
    
      Plugin.prototype.init = function(){
        var self=this, $that = this.$that;
        var latency = this.options.latency;
        var options_top = this.options.top;
        var $parent = $that.offsetParent();
        if($that.attr('data-top')){
          options_top = parseInt($that.attr('data-top'), 10);
        }
        $(document).scroll($.debounce(latency, function(){
          var doc_top = $(this).scrollTop();
          var top = doc_top + options_top - $parent.offset().top;
          $that.animate({'top': [top, 'px'].join('')});
        }));
      };
    
      $.fn[pluginName]= function(options){
        this.each(function(){
          if(!$.data(this, 'plugin_' + pluginName)) {
            $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
          }
        });
      };
      return $.fn[pluginName];
    })(jQuery);
    /```
    
    
    
    
    标签:

      分享到:
      comments powered by Disqus

      22/25ms