就本质而言,开发一个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);
/```