<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>js实现tab标签切换效果- 站长素材</title> <style> *{ margin:0; padding:0; list-style:none;} body{ font-size:12px;} #my_col_guan{width:360px; overflow:hidden;} #my_col_guan #my_menus {display:block;width:100%;padding:0;margin:0;list-style:none;} #my_col_guan #my_menus li {float:left;width:120px;} #my_col_guan #my_menus li a {display:block;line-height:27px;text-decoration:none;padding:0 0 0 5px; text-align:center; color:#333;} #my_menu_con{ width:358px; height:135px; border-top:none} .tag{ padding:10px; overflow:hidden;} .col_guan_selected{background:#C5A069; color:#fff;} </style> </head> <body> <!--代码部分begin--> <div id="my_col_guan"> <!--tag标题--> <ul id="my_menus"> <li><a href="#" class="col_guan_selected">jQuery特效</a></li> <li><a href="#" class="">tab切换</a></li> <li><a href="#" class="">菜单导航</a></li> </ul> <!--二级菜单--> <div id="my_menu_con"> <div class="tag" style="display:block"> 这里是jQuery特效内容列表 </div> <div class="tag" style="display:none"> 这里是tab切换效果 </div> <div class="tag" style="display:none"> 这里是菜单导航效果 </div> </div> </div> <script> var tabs=function(){ function tag(name,elem){ return (elem||document).getElementsByTagName(name); } //获得相应ID的元素 function id(name){ return document.getElementById(name); } function first(elem){ elem=elem.firstChild; return elem&&elem.nodeType==1? elem:next(elem); } function next(elem){ do{ elem=elem.nextSibling; }while( elem&&elem.nodeType!=1 ) return elem; } return { set:function(elemId,tabId){ var elem=tag("li",id(elemId)); var tabs=tag("div",id(tabId)); var listNum=elem.length; var tabNum=tabs.length; for(var i=0;i<listNum;i++){ elem[i].onclick=(function(i){ return function(){ for(var j=0;j<tabNum;j++){ if(i==j){ tabs[j].style.display="block"; //alert(elem[j].firstChild); elem[j].firstChild.className="col_guan_selected"; } else{ tabs[j].style.display="none"; elem[j].firstChild.className=""; } } } })(i) } } } }(); tabs.set("my_menus","my_menu_con");//执行 </script> <!--代码部分end--> </body> </html>
效果图: