<!DOCTYPE> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>div+css+js模拟TAB</title> <style> body{margin:0;padding:0; background:#CCCCCC} a{text-decoration:none} #tabnav ul{padding:0;margin:0} #tabnav li{float:left;list-style:none; padding:10px;} #tabnav li.on{display:inline-block;background:#fff;} #tabcon{ clear:both; background:#009933; padding:10px;text-align:left;color:#fff} .hide {display:none} </style> </head> <body> <div id="tab"> <div id="tabnav"> <ul> <li class="on"><span>TAB1111</span></li> <!--这里弄成 <li class="on"><span>TAB1111</span></li> 就不可以了 --> <li>TAB2222</li> <li>TAB3333</li> <li>TAB4444</li> </ul> </div> <div id="tabcon"> <div> 这里是内容111<br> 这里是内容111<br> 这里是内容111<br> </div> <div class="hide"> 这里是内容222<br> 这里是内容222<br> 这里是内容222<br> </div> <div class="hide"> 这里是内容333<br> 这里是内容333<br> 这里是内容333<br> </div> <div class="hide"> 这里是内容444<br> 这里是内容444<br> 这里是内容444<br> </div> </div> </div> <script> function get_id(id) { return (typeof id == "string") ? document.getElementById(id) : id; } function changeTab(tab_id, con_id, on, type) { var tab_li = get_id(tab_id).getElementsByTagName('li'); var con_div = get_id(con_id).getElementsByTagName('div'); for (var i = 0; i < tab_li.length; i++) { tab_li[i].index = i; if (document.all) { //alert(1) tab_li[i].attachEvent('on' + type, currTab); } else { tab_li[i].addEventListener(type, currTab, false); } } function currTab() { hideAll(); if (document.all) { alert(i) // 4 // alert(this.event.srcElement.innerHTML) // 此处的this传过来的不是tab_li[i] // alert(this.event.srcElement.index) // 只有当点击的元素是 li 时,才有index值。 //this.event.srcElement.className = on; //con_div[this.event.srcElement.index].className = ''; // this.className = on; // con_div[this.index].className = ''; } else { this.className = on; con_div[this.index].className = ''; } } function hideAll() { for (var i = 0; i < con_div.length; i++) { con_div[i].className = 'hide'; tab_li[i].className = ''; } } } changeTab("tabnav", "tabcon", "on", "click"); // changeTab("tabnav", "tabcon", "on" ,"mouseover"); </script> </body> </html>