1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>js制作一个选项卡</title> 6 <style type="text/css"> 7 .tab_title span.active { 8 background:#000; 9 color: #FFF; 10 } 11 .tab_content { 12 border:1px solid #000; 13 padding: 20px; 14 } 15 .tab_content div { 16 display: none; 17 } 18 .tab_content div.active { 19 display: block; 20 } 21 </style> 22 23 <script type="text/javascript"> 24 //1.选取到tab选项卡 2.为选项卡添加事件 25 window.onload = function(){ 26 var arr_tab_span = document.getElementsByTagName(‘span‘); 27 var tab_section = document.getElementById(‘sec_con‘); 28 var arr_tab_div = tab_section.getElementsByTagName(‘div‘); 29 30 //console.log(arr_tab_span); 31 //console.log(tab_section); 32 //console.log(arr_tab_div); 33 34 for (var i=0; i<arr_tab_span.length;i++) { 35 arr_tab_span[i].index = i; 36 arr_tab_span[i].onclick = function(){ //为选项卡点击添加事件 37 for(var j=0;j<arr_tab_span.length;j++){ 38 arr_tab_span[j].className = ‘‘; 39 arr_tab_div[j].className = ‘‘; 40 }//for结束 41 this.className = ‘active‘; 42 arr_tab_div[this.index].className = ‘active‘; 43 44 } 45 }//for结束 46 } 47 </script> 48 49 </head> 50 <body> 51 <div style="width: 500px;"> 52 <nav class="tab_title"> 53 <span class="active">语文</span> 54 <span>数学</span> 55 <span>娱乐</span> 56 </nav> 57 <section class="tab_content" id="sec_con"> 58 <div class="active"> 59 鲁迅是语文课本上的 60 </div> 61 <div> 62 祖冲之是数学课上的 63 </div> 64 <div> 65 孙悟空是娱乐电视里的 66 </div> 67 </section> 68 </div> 69 </body> 70 </html>
代码效果如下
原文地址:https://www.cnblogs.com/html55/p/9768033.html
时间: 2024-10-13 03:06:19