选项卡在我们日常写网页中经常用到,在360浏览器首页中就用到很多的选项卡,我就模仿360首页的选项卡做一个案例,使用面向对象的方法来写。面向对象在这个小案例中会显得很麻烦,但是在大型开发中会简单很多,所以要学会使用。
其主要思想就是,先让所有的div块隐藏,然后让第一个显示,记录每个按钮当前的位置,然后设置其他div的隐藏,当前div的显示。
最终效果图如下:
代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #div1 input{ width: 50px; background: white; } /*选中时候的样式*/ #div1 input.active{ background: yellow; border-top-color: #008000; font-weight:900 ; } #div1 div{ width: 200px; height: 300px; background: #FFF; border: dashed; display: none; } </style> <script> window.onload=function(){ new TabSwitch('div1'); }; function TabSwitch(id){ var _this=this; var oDiv=document.getElementById('div1'); this.aBtn=oDiv.getElementsByTagName('input'); this.aDiv=oDiv.getElementsByTagName('div'); for(var i=0;i<this.aBtn.length;i++){ this.aBtn[i].index=i; this.aBtn[i].onclick=function () { _this.fnClick(this); }; } }; TabSwitch.prototype.fnClick=function (oBtn) { for (var i=0;i<this.aBtn.length;i++){ this.aBtn[i].className=''; this.aDiv[i].style.display='none'; } oBtn.className='active'; this.aDiv[oBtn.index].style.display='block'; }; </script> </head> <body> <div id="div1"> <input id="btn1" type="button" value="热播" class="active"> <input id="btn2" type="button" value="视频"> <input id="btn3" type="button" value="电影"> <input id="btn4" type="button" value="花边"> <div style="display: block;">热播电视剧</div> <div>热播视频</div> <div>热播电影</div> <div>花边新闻</div> </div> </body> </html>
eee