HTML+JS+DOM【选项卡自动切换】
最终效果图(鼠标无操作会自动切换选项卡):
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="gb2312" /> 5 <title>无标题文档</title> 6 <style> 7 body, ul, li { 8 font-family:"黑体"; 9 margin:0; 10 padding:0; 11 } 12 ul, li { 13 list-style:none; 14 } 15 .tab { 16 width:408px; 17 margin:200px auto auto auto; 18 } 19 .hide { 20 display:none; 21 } 22 #tab_head { 23 height:31px; 24 border-top:2px solid #03F; 25 border-bottom:1px solid #090; 26 } 27 #tab_head li { 28 float:left; 29 width:100px; 30 height:30px; 31 line-height:30px; 32 margin:0 0px; 33 text-align:center; 34 border:1px solid #ccc; 35 border-bottom:none; 36 background:#f5f5f5; 37 cursor:pointer 38 } 39 #tab_head .current { 40 position:relative; 41 height:31px; 42 margin-bottom:-1px; 43 background:#fff; 44 } 45 #tab_body { 46 border:1px solid #ccc; 47 border-top:none; 48 padding:20px; 49 height:150px; 50 text-indent:2em; 51 } 52 </style> 53 <script> 54 window.onload = function(){ 55 var tab_head = document.getElementById("tab_head"); 56 var tab_head_li = tab_head.getElementsByTagName("li"); 57 var tab_body = document.getElementById("tab_body"); 58 var tab_body_div = tab_body.getElementsByTagName("div"); 59 var len = tab_head_li.length; 60 var i=0; 61 var timer = null; 62 var num=0; 63 64 //1.进行初始化设置,设置每个导航的onmouseover和onmouseout的事件 65 for(i=0; i<len; i++){ 66 tab_head_li[i].index = i; 67 tab_head_li[i].onmouseover = function(){ 68 clearInterval(timer); 69 num = this.index; 70 tab_bodychange(); 71 } 72 tab_head_li[i].onmouseout = function(){ autoplay(); } 73 } 74 75 //辅助函数,将num当前置为显示 76 function tab_bodychange(){ 77 for(i=0; i<len; i++){ 78 tab_head_li[i].className = ''; 79 tab_body_div[i].className = 'hide'; 80 } 81 tab_head_li[num].className = 'current'; 82 tab_body_div[num].className = ''; 83 } 84 //辅助函数,自动循环改变 85 function autoplay(){ 86 timer = setInterval(function(){num=(++num)%len;tab_bodychange();},500); 87 } 88 autoplay();//2.进入自动循环 89 } 90 </script> 91 </head> 92 <body> 93 <div class="tab"> 94 <ul id="tab_head"> 95 <li class="current">HOME</li> 96 <li>VIDEO</li> 97 <li>IMAGE</li> 98 <li>MUSIC</li> 99 </ul> 100 <div id="tab_body"> 101 <div>HOME 标签</div> 102 <div class="hide">VIDEO 标签</div> 103 <div class="hide">IMAGE 标签</div> 104 <div class="hide">MUSIC 标签</div> 105 </div> 106 </div> 107 </body> 108 </html>