JS代码
(function (w) { //tab对象 function Tab(config) { //定义变量,防止变量污染 this.tabMenus=null; this.tabMains=null; if(config){ this._init(config); } } //为原型添加属性,防止内存重复创建 Tab.prototype={ _init:function (config) { //初始化元素 this.initElements(config); this.initEvent(); if(config.auto){ this.autoPlay(); } }, initElements:function (config) { var tabMenu=document.getElementById(config.tabMenu); var tabMain=document.getElementById(config.tabMain); this.tabMenus=tabMenu.children; this.tabMains=tabMain.children; }, initEvent:function () { for(var i=0;i<this.tabMenus.length;i++){ var li=this.tabMenus[i]; li.index=i; //定义this变量存储,闭包环境可以调用此变量 var that=this; li.onclick=function () { that.change(this); } } }, change:function (tabMenu) { for(var i=0;i<this.tabMenus.length;i++){ this.tabMenus[i].className=""; this.tabMains[i].className="main"; } tabMenu.className="active"; this.tabMains[tabMenu.index].className+=" select"; }, autoPlay:function () { var index=0; var that=this; setInterval(function () { index++; if(index>=that.tabMenus.length){ index=0; } that.change(that.tabMenus[index]); },2000); } } //将插件暴露给windows w.Tab=Tab; })(window)
HTML代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" type="text/css" href="tab.css"> </head> <body> <div class="wrapper"> <ul class="tab" id="menu"> <li class="active">国际大牌<span>◆</span></li> <li>国妆名牌<span>◆</span></li> <li>清洁用品<span>◆</span></li> <li>男士精品</li> </ul> <div class="products" id="main"> <div class="main select"><a href="#"><img src="imgs/guojidapai.jpg"></a></div> <div class="main"><a href="#"><img src="imgs/guozhuangmingpin.jpg"></a></div> <div class="main"><a href="#"><img src="imgs/qingjieyongpin.jpg"></a></div> <div class="main"><a href="#"><img src="imgs/nanshijingpin.jpg"></a></div> </div> </div> </body> <script type="text/javascript" src="tab.js"></script> <script> var tb=new Tab({ tabMenu:"menu", tabMain:"main", auto:true }); </script> </html>
css代码
html,body,ul,li { margin: 0; padding: 0; } ul{ list-style: none; } .wrapper { margin: 0 auto; width: 1000px; height: 475px; margin-top: 100px; } .wrapper .tab { width: 320px; height: 36px; border: 1px solid #ddd; border-bottom: 0; } .wrapper .tab li{ float:left; width: 80px; height: 34px; line-height: 34px; cursor: pointer; text-align: center; border-top: 4px solid #fff; position: relative; } .wrapper .tab .active{ border-top: 4px solid red; } .wrapper .tab span{ width: 1px; height: 14px; background-color: #ddd; position: absolute; right:0px; top:10px; overflow: hidden; } .wrapper .products{ width: 1002px; height: 476px; border:1px solid #ddd; } .wrapper .products .main{ float: left; display: none; } .wrapper .products .select{ display: block; }