根据点击的按钮切换选项卡内容(JS代码)
<style type="text/css"> /*外层*/ .Box { width: 240px; border: 1px solid #000; margin: 100px auto; padding: 20px; } /*选项卡*/ .con { width: 100%; height: 200px; border: 1px solid #000; margin-top: 10px; display: none; } /*当前按钮的效果*/ .current { padding: 0px; max-width: 900px; } </style> <div class="Box" id="box"> <button class="current">one</button> <button>two</button> <button>three</button> <button>four</button> <div class="con" style="display:block">one</div> <div class="con" >two</div> <div class="con" >three</div> <div class="con" >four</div> </div>
1 <script> 2 3 /* 获取盒子 */ 4 5 var box=document.getElementById("box"); 6 7 /* 获取盒子内的按钮 ,选项卡 */ 8 9 var btns=box.getElementsByTagName("button"); 10 11 var divs=box.getElementsByTagName("div"); 12 13 /*遍历按钮,分别设置按钮index属性为从0到按钮长度-1 的数字*/ 14 15 for(var i = 0 ; i<btns.length; i++){ 16 17 btns[i].setAttribute("index",i); 18 19 /*当按钮被单机的时候,执行动画*/ 20 21 btns[i].onclick=function(){ 22 23 /*1,把所有的按钮上的CLASS去掉,隐藏选项卡(通过迭代的方式)*/ 24 25 for(var j =0 ; j<btns.length ; j++){ 26 27 btns[j].removeAttribute("class"); 28 29 divs[j].style.display="none"; 30 31 } 32 33 /*2,设置this 被点击的按钮的CLASS为CURRENT,被点击的按钮对应的DIV为显示状态*/ 34 35 this.setAttribute("class","current"); 36 37 divs[this.getAttribute("index")].style.display="block"; 38 39 } 40 41 } 42 43 </script>