js實現側邊導航欄展開和摺疊

效果:左側導航欄,點擊展開,顯示子菜單。再次點擊,菜單摺疊。
代碼javascript

<!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=gb2312" />
<title>檸檬酒店</title>
<style> /*設置導航每一個主菜單的樣式*/ .main_nav{ display:block; width:200px; padding:10px; font-weight:bold; background-color:#BADFF2; } li{list-style:none;} #globalNav { position:absolute; top:3px; left:2px; } /*導航中每一個子菜單的樣式*/ #globalNav ul li a{ margin:auto 10px; display:block; width:140px; color:#fff; font-weight:bold; text-decoration:none; } #globalNav li ul li a{ background:#6DBBE1; } #globalNav li ul li a:hover{ background:#BCF2F0;<!--鼠標通過的顏色--> } </style>
<script type="text/javascript" > function initTree(t) { var tree=document.getElementById(t);//生成樹 tree.style.display="none";//設置樣式爲隱藏形式,不顯示 var lis=tree.getElementsByTagName("li"); for(var i=0;i<lis.length;i++) { //取出主要的導航欄 lis[i].id="li"+i; var uls=lis[i].getElementsByTagName("ul"); //子導航欄 if(uls.length!=0) { uls[0].id="ul"+i; uls[0].style.display="none"; var as=lis[i].getElementsByTagName("a"); //子導航欄的內容 as[0].id="a"+i; as[0].className="folder"; as[0].href="#this"; as[0].tget=uls[0]; as[0].onclick=function() { openTag(this,this.tget); } } } tree.style.display="block"; } function openTag(a,t) { if(t.style.display=="block") { //點擊一些展開,再點擊一下摺疊 t.style.display="none"; a.className="folder"; } else { t.style.display="block"; a.className=""; } } window.onload=function() { initTree("globalNav"); } </script>
</head>
<body id="index">
<ul id="globalNav">
  <li class="main_nav"><a href="#">房間信息</a>
    <ul>
      <li><a href="nullroom.php" target="mainFrame">空房</a></li>
      <li><a href="room.php" target="mainFrame">全部房間</a></li>
      <li><a href="orderroom.php" target="mainFrame">被訂房間</a></li>
      <li><a href="register/room.html" target="mainFrame">錄入房間信息</a></li>
    </ul>
  </li>
  <li class="main_nav"><a href="#">房客信息</a>
    <ul>
      <li><a href="register/custom.html" target="mainFrame">錄入房客信息</a></li>
      <li><a href="custom_info.php" target="mainFrame">客史檔案</a></li>
    </ul>
  </li>
  <li class="main_nav"><a href="#">訂單</a>
    <ul>
      <li><a href="register/order.html" target="mainFrame">錄入訂單信息</a></li>
      <li><a href="order.php" target="mainFrame">查看訂單</a></li>
    </ul>
  </li>
  <li class="main_nav"><a href="#">會員</a>
    <ul>
      <li><a href="register/member.html" target="mainFrame">錄入會員信息</a></li>
      <li><a href="member.php" target="mainFrame">查看會員信息</a></li>
    </ul>
  </li>
  <li class="main_nav"><a href="#">財務</a>
    <ul>
      <li><a href="register/cash.html" target="mainFrame">錄入財務信息</a></li>
      <li><a href="cash.php" target="mainFrame">查看財務信息 </a></li>
    </ul>
  </li>
  <li class="main_nav"><a href="login/login.html" target="_parent">退出</a></li>
</ul>
</body>
</html>