利用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的內建特性。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章