面向对象版Tab栏切换

时间:2022-06-30 23:06:16
<div class="wrapper" id="wrapper">
<ul class="tab" id="tab-menu">
<li class="tab-item active">国际大牌<span>◆</span></li>
<li class="tab-item">国妆名牌<span>◆</span></li>
<li class="tab-item">清洁用品<span>◆</span></li>
<li class="tab-item">男士精品</li>
</ul>
<div class="products" id="tab-main">
<div class="main selected">
<a href="###"><img src="imgs/guojidapai.jpg" alt=""/></a>
</div>
<div class="main">
<a href="###"><img src="imgs/guozhuangmingpin.jpg" alt=""/></a>
</div>
<div class="main">
<a href="###"><img src="imgs/qingjieyongpin.jpg" alt=""/></a>
</div>
<div class="main">
<a href="###"><img src="imgs/nanshijingpin.jpg" alt=""/></a>
</div>
</div>
</div>
var tb = new Tab({
tabMenu: "tab-menu", // 指定tab栏菜单id
tabMain: "tab-main", // 指定tab栏内容id
auto: true // 是否自动播放
});

面向对象封装

function Tab(obj) {
this.tabMenus = null;
this.tabMains = null;
if(obj) {
this._init(obj);
}
}
Tab.prototype = {
constructor: Tab,
timer : null,
_init:function(obj){
this.initEle(obj);
this.click();
if(obj.auto){
this.autoPlay();
} },
initEle:function(obj){
var tabMenu = document.getElementById(obj.tabMenu);
var tabMain = document.getElementById(obj.tabMain);
this.tabMenus = tabMenu.children;
this.tabMains = tabMain.children;
},
click: function() {
var that = this;
for(var i=0,len=this.tabMenus.length;i<len;i++) {
this.tabMenus[i].onclick = function(){
that.show(this);
that.autoPlay(this.index);
}
}
},
show: function(currentLi) {
for(var i=0,len=this.tabMenus.length;i<len;i++) {
this.tabMenus[i].index = i;
this.tabMenus[i].className = "tab-item";
this.tabMains[i].style.display = "none";
}
currentLi.className += " active";
this.tabMains[currentLi.index].style.display = "block";
},
autoPlay: function(currentIndex){
var that = this;
var index = 0;
if(currentIndex !== undefined && currentIndex !== ""){
index = currentIndex;
}
clearInterval(this.timer);
this.timer = setInterval(function(){
index++;
if(index == that.tabMenus.length){
index = 0;
}
that.show(that.tabMenus[index]);
},2000);
}
}

注意事项:

这里要注意timer的位置,如果将timer放在构造函数里如this.timer=null,则_init()方法要用新创建出的对象来调用timer才生效(tb._init())
如果在构造函数里使用 this._init(obj);来初始化,则timer要放到原型对象里(timer:null)才生效
这里的生效是指清除定时器时clearInterval(this.timer); this.timer为同一个对象 正常情况下this.timer值为null,未生效的情况下值为undefined
由于一些经验不足上面的一段解释是错误的,造成timer值为Undefined的原因为this.timer=null应该在调用方法_init()之前定义