布局很简单。第一个选项卡box,第二个选项卡box2,这体现了面向对象构造函数级原型最大的优点 ,复用!
<div class="box" id="box"> <input type="button" value="按钮1" class="on" /> <input type="button" value="按钮2" /> <input type="button" value="按钮3" /> <div class="show">11111</div> <div>22222</div> <div>33333</div> </div> <div class="box" id="box2"> <input type="button" value="按钮1" class="on" /> <input type="button" value="按钮2" /> <input type="button" value="按钮3" /> <div class="show">11111</div> <div>22222</div> <div>33333</div> </div>
样式我就不上了
JS代码,不明白看可以看下注释
//元素获取 function Tab(id){//Tab 构造函数 this.oBox=document.getElementById(id); this.aBtn=this.oBox.getElementsByTagName('input'); this.aDiv=this.oBox.getElementsByTagName('div'); this.iNow=0; this.init();//选项卡操作在这里执行 } //事件操作 Tab.prototype.init=function (){//Tab原型 var _this=this;//this 赋值,内部事件函数不能直接使用this for(var i=0; i<this.aBtn.length; i++){ this.aBtn[i].index=i; this.aBtn[i].onclick=function (){ _this.iNow=this.index;//同理iNow赋值 tab(); }; } //选项卡核心 function tab(){//这个是提出公共部分 for(var i=0; i<_this.aBtn.length; i++){ _this.aBtn[i].className=''; _this.aDiv[i].className=''; } _this.aBtn[_this.iNow].className='on'; _this.aDiv[_this.iNow].className='show'; } };
最后就是调用了,也可以说实例化,不是实例化的话 ,是用不了的。
window.onload=function (){ new Tab('box'); new Tab('box2'); };