頁籤(Tab)是收斂資訊、節省版面空間的經典元件。網路上這類範例很多,這篇記錄一下我的實作思路,以及幾個容易忽略的細節。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "https://www.w3.org/TR/html4/strict.dtd"> <html xmlns="https://www.w3.org/1999/xhtml" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JQueryProject1</title> <meta name="author" content="Frank_Ren" /> <link type="text/css" rel="stylesheet" href="css/myCSS.css" /> <script type="text/javascript" src="js/jquery-1.8.1.min.js"></script> <script type="text/javascript" src="js/myJSFile.js"></script> <!-- Date: 2012-09-17 --> </head> <body> <div id="contenTab"> <ul> <li class="showTab"><a href="/">標簽1</a></li> <li><a href="/">標簽2</a></li> <li><a href="/">標簽3</a></li> </ul> <div id="content"> <div class="showContent">這是內容1</div> <div>這是內容2</div> <div>這是內容3</div> </div> </div> </body> </html>
結構上刻意讓「標籤清單」與「內容區」並列,且兩邊的項目順序一一對應。這個對應關係是後面用索引配對的基礎。
a{
display: block;
text-decoration: none;
color:white;
}
#contenTab ul{
list-style: none;
padding:0px;
margin:0px;
}
#content div.showContent{
line-height:100px;
display: block;
background-color:#B0C4DE;
}
.showTab{
background-color:#B0C4DE;
border-bottom: 1px solid #B0C4DE;
}
div li{
background-color:#5F9EA0;
border-bottom: 1px solid white;
float: left;
border-right: 1px solid white;
color:black;
height:30px;
width:60px;
line-height: 30px;
text-align: center;
}
#content div{
background-color:#B0C4DE;
display:none;
clear: left;
width:300px;
height: 100px;
}
兩個關鍵技巧:float: left 讓 li 橫向排列;#content div 預設 display:none,只有帶 showContent 的那個才顯示。標籤的選中態也是同樣邏輯——靠 showTab 這個 class 決定底色與下邊框(下邊框設成與內容區同色,視覺上就和內容連成一體)。
$(function(){
$("#contenTab li").each(function(){
var tab = $(this);
var timeoutID;
tab.hover(function(){
timeoutID = setTimeout(function(){
$(".showTab").removeClass("showTab");
$(".showContent").removeClass("showContent");
tab.addClass("showTab");
$($("#content div").get($("#contenTab li").index(tab))).addClass("showContent");
},300);
},function(){
clearTimeout(timeoutID);
});
});
});
核心那行值得細看:$("#contenTab li").index(tab) 取得目前 hover 的標籤在清單中的位置,再用 $("#content div").get(位置) 取出對應的內容 div。標籤與內容的配對就這樣完成了,不必為每個項目寫死 id。
游標變手形。範例中把 li 的內容包進 <a> 來達到效果,但其實有更簡單的做法:直接給 li 加上 cursor: pointer; 即可。
為什麼要延遲 300 毫秒。setTimeout 這段是整個範例最實用的部分。滑鼠在頁籤列上快速掃過時,若每個 hover 都立即切換,畫面會瘋狂閃動。加上延遲後:滑鼠停留超過 300ms 才切換;若在 300ms 內離開,mouseleave 會執行 clearTimeout(timeoutID),把計時器取消,切換就不會發生。這個「防抖」思路在各種 hover 效果裡都能派上用場。
可以再改進的地方。目前用 hover 觸發,在觸控裝置上不存在 hover 這個狀態,建議同時綁定 click,或改用點擊作為主要觸發方式。另外,若標籤數量會動態變化,把 index 對應改成用 data 屬性存索引會更穩定——一旦中間插入或刪除項目,位置索引就會錯位。
今天就到這裡,希望對你有所幫助。