經過實踐,發現我不是一個能夠堅持的人,所以一有計劃馬上執行,爲了每天保持學習,敲代碼,所以不斷看視頻教程,看書,當年成爲學渣就是因爲不能重複看一本書。爲了分擔家裏負擔,好書重複翻看,好的視頻教程重複看,忍忍也就過去了,我需要提升!
關於插件,之前文章講過,this指向要分清楚,再次強調一下。若在插件內部,則指向當前插件對象;若插件中還有內部函數,例如計時器,事件則指向DOM元素。如果記不住,沒關係,你可以在瀏覽器控制檯中輸出當前this,一目瞭然。
關於jQuery插件之tab選項卡插件初步開發,裏面並沒有做插件擴展,也沒有做防止全局變量名衝突,當然也沒有自動初始化,只是簡單的練習。
首先上結構標籤代碼,由於沒有做類名參數處理,暫時固定名字。
<div id="tab" class="js-tab" data-config='{
"type":"mouseover",
"effect":"fade",
"show":1,
"auto":1000}'>
<ul class="tab-nav">
<li class="active">1</li>
<li>2</li>
<li>3</li>
</ul>
<ul class="tab-wrap">
<li class="tab-item active"></li>
<li class="tab-item"></li>
<li class="tab-item"></li>
</ul>
</div>
接下來tab插件代碼
// 該插件根據慕課網tab插件教程練手
+(function($){
'use strict';//嚴格模式
// tab類
var Tab=function(tab){
this.tab=tab;
var _this=this; //保存當前對象Tab
this.timer=null;
this.loop=0;
// 默認配置參數
this.config={
type:"mouseover",
effect:"default",
show:1,
auto:false
};
this.getConfig()&&$.fn.extend(this.config,this.getConfig());
//保存插件對象及配置參數
this.tabNav=this.tab.find('.tab-nav li');
this.tabItem=this.tab.find('.tab-wrap .tab-item');
if(this.config.type==="click"){
this.tabNav.bind(this.config.type,function(e){
//bind函數中間,this指向就是DOM元素,所以就用_this
_this.currentChange($(this));
});
}else{
this.tabNav.bind("mouseover",function(e){
_this.currentChange($(this));
});
}
//自動切換
if(this.config.auto){
this.autoPlay(this);
this.tab.hover(function(){
clearInterval(_this.timer);//鼠標經過清除自動
},function(){
_this.autoPlay(_this);
});
}
}
// 原型
Tab.prototype={
// 獲取配置參數
getConfig:function(){
var config=this.tab.attr('data-config');//獲取元素配置參數
//轉義config字符串爲對象
if(config&&config!=null){return $.parseJSON(config)}
else{
return null;
}
},
//選項卡切換,
currentChange:function(cur){
var index=cur.index();//獲取當前li的索引值
cur.addClass("active").siblings().removeClass("active");
if(this.config.effect==="default"){
this.tabItem.eq(index).addClass("active").siblings().removeClass("active");//爲當前元素添加active,移除兄弟元素的active
}else if(this.config.effect==="fade"){
this.tabItem.eq(index).stop().fadeIn().siblings().stop().fadeOut();
}
if(this.config.auto){
this.loop=index;
}
},
//自動切換
autoPlay:function(_this){
var tabLength=this.tabItem.size();//tab循環個數
this.timer=setInterval(function(){
_this.loop++;
if(_this.loop>=tabLength){
_this.loop=0;
}
_this.currentChange(_this.tabNav.eq(_this.loop));//傳入li,進行自動切換
},this.config.auto);
}
}
// 擴展參數到jQuery方法上,實現鏈式調用,如$('xx').Tab().css()
$.fn.extend({
Tab:function(){
this.each(function(){
new Tab($(this));
});
return this; //jQuery鏈式調用
}
});
// 註冊全局變量
window.Tab=Tab;
})(jQuery);
最後上完整代碼