注意事项
1、给li元素注册事件,函数里面的this指的li元素,那么我们可以在注册事件之前将Tab对象用that=this进行保存
2、使用沙箱模式,所以暴露给外面的变量使用的是window.tab,将window作为参数传递进去
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { padding: 0; margin: 0; } .clearfix:after { content: ''; visibility: hidden; display: block; clear: both; } .container { width: 800px; margin: 120px auto; } .tab { line-height: 40px; } .tab ul { width: 500px; list-style: none; border-top: 1px solid gray; border-left: 1px solid gray; border-right: 1px solid gray; } .tab ul li { float: left; width: 100px; height: 40px; text-align: center; position: relative; } .tab ul li:after { content: ''; display: block; width: 1px; height: 14px; border-right: 1px solid gray; position: absolute; top: 13px; right: 0; } .tab ul li:nth-child(5):after { visibility: hidden; } .tab ul li.current { color: red; } .tab ul li.other { color: black; } .main { height: 500px; border: 1px solid gray; } .main div { height: 500px; text-align: center; line-height: 500px; font-size: 60px; display: none; } .main div.current { display: block; } </style> </head> <body> <div class="container"> <div class="tab"> <ul class="clearfix" id="tab-menu"> <li class="current">童装</li> <li>男装</li> <li>女装</li> <li>冬天</li> <li>夏天</li> </ul> </div> <div class="main" id="tab-main"> <div class="current">童装</div> <div>男装</div> <div>女装</div> <div>冬天</div> <div>夏天</div> </div> </div> <script> (function (w) { function Tab(config) { this.tabMenus = null; this.tabMains = null; if (config) { this._init(config) } } Tab.prototype = { constructor: Tab, //初始化工作 _init: function (config) { this.initElements(config); this.initEvent(); if (config.auto) { this.autoPlay(); } }, initEvent: function () { for (var i = 0; i < this.tabMenus.length; i++) { var li = this.tabMenus[i]; li.index = i; //that存储当前对象也就Tab创建出来的对象 var that = this; li.onclick = function () { //that还是只想Tab创建出来的对象 //this指的就是当前点击事件触发的这个li that.change(this); }; } }, initElements: function (config) { //根据config里的id //给当前对象的tabMenus和tabMains赋值 var tabMenu = document.getElementById(config.tabMenu); var tabMain = document.getElementById(config.tabMain); this.tabMenus = tabMenu.children; this.tabMains = tabMain.children; }, change: function (tabMenu) { //1.让所有的li变暗 for (var i = 0; i < this.tabMenus.length; i++) { this.tabMenus[i].className = "other"; //3.让所有div隐藏 this.tabMains[i].style.display = "none"; } //2.让当前的li变亮 tabMenu.className = 'current'; //4.对应的div显示 this.tabMains[tabMenu.index].style.display = "block"; }, autoPlay: function () { var index = 0; var that = this; setInterval(function () { index++; if (index == that.tabMenus.length) { index = 0; } that.change(that.tabMenus[index]); }, 2000); } } w.Tab = Tab; })(window); var tb = new Tab({ tabMenu: "tab-menu", // 指定tab栏菜单id tabMain: "tab-main", // 指定tab栏内容id auto: true // 是否自动播放 }); </script> </body> </html>