您的位置:首页 > Web前端 > JQuery

jQuery 插件简单模板

2014-03-21 12:08 344 查看
/*!
* Copyright yunos.com All rights reserved.
* jquery.scrollspy.js
* @author v10258@qq.com
* @version 0-0-1
*/
(function ($) {

// contructor function
var ScrollSpy = function (element, options) {
this.element = $(element);
this.options = $.extend({}, ScrollSpy.defaults, options || {});
this.anchorArr = $(element).find('a');
this.init();
};

// default config
ScrollSpy.defaults = {
scrollEle: $(window)
};

// prototype
ScrollSpy.prototype = {
constractor: ScrollSpy,
init: function () {
var self = this,
element = this.element,
scrollEle = this.options.scrollEle,
anchorData,
scrollTop;

scrollEle.on('scroll', function () {
// The realization of the bad dynamic acquisition
anchorData = self.getAnchorData();
scrollTop = $(this).scrollTop();
for (var i = 0, len = anchorData.length; i < len; i++) {
if (anchorData[i].min <= scrollTop && scrollTop < anchorData[i].max) {
$(anchorData[i].author).parent().addClass('current').siblings().removeClass('current');
break;
}
}
});
},
getAnchorData: function () {
var anchorArr = this.anchorArr,
active,
activeDom,
anchorTargetArr = [];

anchorArr.each(function (i, n) {
active = $($(this).attr('href'));
activeDom = active[0];
anchorTargetArr.push({
ele: activeDom,
author: this,
min: active.offset().top,
max: active.offset().top + active.height()
});
});
return anchorTargetArr;
},
distroy: function(){
this.element.removeData('scrollspy');
this.options.scrollEle.off('scroll');
}
};

// bridging
$.fn.scrollspy = function (option) {
return this.each(function () {
var $this = $(this),
data = $this.data('scrollspy'),
options = typeof option == 'object' && option;

if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options)));
if (typeof option == 'string') data[option]();
});
};
})(jQuery);


  个人感觉,写插件,插件的具体结构,能用原生结构,还是用原生结构的好,最后桥接在jquery上.

  如果像下面这样,看起来是不是有点 蛋疼呢。

(function ($) {
$.love.defaults = {
// ......
};
$.love = function (element, o) {
this.element = element;
this.options = $.extend({}, $.love.defaults, o);
// ......
};

var $love = $.love;
$love.fn = $love.prototype = {
verson: '0.0.1'
// ......
};
$love.fn.extend = $love.extend = $.extend;

$love.fn.extend({
metod: function () {

}
// ......
});

$.fn.ilove = function (o) {
// ......
};
})(jQuery);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: