首页 > 代码库 > 面向对象版Tab栏切换
面向对象版Tab栏切换
<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
面向对象版Tab栏切换
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。