DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
實作 CSS 垂直樹狀下拉選單
編輯:CSS詳解     

做一個垂直的樹狀下拉選單,第一步——建立選單架構——最為關鍵。最好的方法是用 ul 來呈現各選項的從屬關係。聽起來複雜,其實一路寫下去就好:

<ul>
 <li><a href="#">Home</a></li>
 <li><a href="#">About</a>
  <ul>
   <li><a href="#">History</a></li>
   <li><a href="#">Team</a></li>
   <li><a href="#">Offices</a></li>
  </ul>
 </li>
 <li><a href="#">Services</a>
  <ul>
   <li><a href="#">Web Design</a></li>
   <li><a href="#">Marketing</a></li>
   <li><a href="#">Hosting</a></li>
  </ul>
 </li>
</ul>

第二步:視覺上的修飾

上面的程式碼直接用瀏覽器打開會非常難看,所以我們先加點樣式,別讓外觀讓你失去繼續做的動力。首先去掉討人厭的項目符號,並定義選單寬度:

ul {
 margin: 0;
 padding: 0;
 list-style: none;
 width: 150px;
 border-bottom: 1px solid #ccc;
}

接著定義內容部分。很幸運,列表預設就是垂直排列,正合我們的需求。定位方式設為相對定位,因為子選單要在相對位置上做絕對定位:

ul li {
 position: relative;
}

再來定義子選單內容,用 left 與 top 讓它們顯示在主選單右側,並用 display:none 讓它們預設隱藏:

li ul {
 position: absolute;
 left: 149px;
 top: 0;
 display: none;
}

最後修飾一下 a 元素:

ul li a {
 display: block;
 text-decoration: none;
 color: #777;
 background: #fff;
 padding: 5px;
 border: 1px solid #ccc;
 border-bottom: 0;
}

但因為 IE 有顯示上的 bug,得加上這段修正(同時對 IE Mac 隱藏):

/* Fix IE. Hide from IE Mac \*/
* html ul li { float: left; }
* html ul li a { height: 1%; }
/* End */

第三步:讓它動起來

我們希望在滑鼠移到主選單時顯示子選單:

li:hover ul { display: block; }

好了,可以測試了!遺憾的是,就現階段而言,這段程式碼在 IE 上還無法做出我們想要的結果。要讓 IE 有一樣的效果,得補上一小段 JavaScript,並不繁瑣:

startList = function() {
if (document.all && document.getElementById) {
 navRoot = document.getElementById("nav");
 for (i=0; i<navRoot.childNodes.length; i++) {
  node = navRoot.childNodes[i];
  if (node.nodeName=="LI") {
   node.onmouseover=function() {
    this.className+=" over";
   }
   node.onmouseout=function() {
    this.className=this.className.replace(" over", "");
   }
  }
 }
}
}
window.onload=startList;

最後把 hover 規則補上 li.over,並在最外層的 ul 加上 id="nav",選單就能跨瀏覽器正常運作了:

li:hover ul, li.over ul {
 display: block;
}
<ul id="nav">

剩下的就看你如何妝點,動手做一個更好看的版本吧!

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved