利用jquery进行插件的开发

在开展一个前端项目的时候,由于进度的限制,我们不得不去寻找一些开源的插件来使用,但是这些插件不一定能完全适合我们的项目需求,这时候就需要我们自己修改别人的插件或者开发自己的插件。虽然说不要重复造轮子,但是开发插件是一个非常高效的学习方式。现在流行的插件很多都是基于jquery开发的,那么我们如何利用jquery开发自己的插件呢?

有三种方式

1.利用$.extend()来扩展jquery

$.extend({

sayhello:function(name){

alert('hello'+(name?name:'mingkai'));

}

})

$.sayhello();//hello mingkai

$.sayhello('xiaowang');//hello xiaowang 

这种方法非常简单,相当于利用jquery扩展一个方法方便你调用,但是不能发挥jquery操作dom的优势。

2.通过$.fn向jquery中的dom添加新的方法,这种方法是非常常用的,一般的插件都是用这种方法进行开发。下面是我自己写的一个轮播图插件,用匿名函数的方式保护命名空间,传入jquery方便我们使用$的习惯。面向对象的方法使结构更加清晰。

(function($){
//轮播图
function Carousel(Carousel,options){
var width='-'+Carousel.width();
Carousel.children('img').each(function(index,ele){
$(ele).attr('data-n',(index+1));
if(index!=0){
$(ele).css('left',Carousel.width()*1.05);
}
})
var func = this;
this.t =setInterval(function(){
func.show(Carousel,width);
},options.v)
this.set_time=function(){
this.t=(function(){
var t = setInterval(function(){
func.show(Carousel,width);
},options.v)
return t;
})();
}
}
Carousel.prototype.show=function(Carousel,width){
if(width<0){
//向左轮播
$('.active').animate({'left':width});
$('.active').next().animate({'left':0},function(){
var active = $('.active').removeClass('active').clone();
active.css('left',Carousel.width());
Carousel.append(active);
Carousel.children('img').eq(1).removeAttr('style').css({'width':Carousel.width()});
//删除dom后浏览器会重绘文档,再解析一遍设置的style
Carousel.children('img').eq(0).remove();
Carousel.children('img').eq(0).addClass('active');
$('.hint').html($('.active').attr('data-n'));
});
}else{
//向右轮播
var w = '-'+width+'px';
var last = Carousel.children('img:last-child').clone();
last.css({'left':w});
Carousel.prepend(last);
$('.active').animate({'left':width*1.05});
Carousel.children('img').eq(0).animate({'left':0},function(){
Carousel.children('img:last-child').remove();
$(this).addClass('active');
$(this).next().removeClass('active');
$('.hint').html($('.active').attr('data-n'));
})


}
}
$.fn.Carousel=function(options){
var defaults={};
var num = $("<div class='hint' style='position:absolute;top:980px;opacity:0.5;z-index:100;background-color:red;height:50px;width:50px;font-size:50px'>1</div>");
this.after(num);
this.css({'height':$(this).children('.active').height()*7});
this.children('img').css({'width':$(this).width()});
options = $.extend(defaults,options||{});
var obj = new Carousel(this,options);
var l_w = '-'+this.width();
var r_w = this.width();
this.on('swipeleft',function(){
obj.show($(this),l_w);
clearInterval(obj.t);
obj.set_time();
});
this.on('swiperight',function(){
obj.show($(this),r_w);
clearInterval(obj.t);
obj.set_time();
});
//返回当前调用对象,该this是一个jquery包装好点对象,支持链式调用
return this;


}
})(jQuery)

3.通过$.widget()应用jQuery UI的部件工厂方式创建

这种方式是比较高级的,开发出来的部件有很多jquery的内建特性。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值