
Tab 切換的骨幹是「索引對齊」:標題列的第 n 個項目,對應內容區的第 n 個區塊。滑過或點擊某個標題時,讓它高亮,並讓同索引的內容顯示、其餘隱藏。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Tab</title>
<script src="js/jquery-1.11.1.js"></script>
<style>
*{ margin: 0; padding: 0; }
div{ width: 184px; height: 100px; border: 1px solid gray; display: none; }
.tab{ list-style: none; width: 200px; overflow: hidden; }
.tab li{
float: left; width: 60px; border: 1px solid red; height: 30px;
line-height: 30px; vertical-align: middle; text-align: center; cursor: pointer;
}
.on{ display: block; }
.cur{ background: red; color: #fff; }
</style>
<script>
$(function(){
$('.tab li').hover(function(){
$(this).addClass('cur').siblings().removeClass('cur');
$("div").eq($(this).index()).addClass("on").siblings().removeClass('on');
})
})
</script>
</head>
<body>
<ul class="tab">
<li class="cur">最新</li>
<li>熱門</li>
<li>新聞</li>
</ul>
<div class="on">11</div>
<div>22</div>
<div>33</div>
<br/>
<input type="text" value="你好請輸入密碼"
onfocus="if(this.value=='你好請輸入密碼'){value=''}"
onblur="if(this.value==''){value='你好請輸入密碼'}">
</body>
</html>
三個關鍵 API:$(this).index() 取得目前項目在群組中的序號、.eq() 依序號選取對應內容、.siblings().removeClass() 一鍵清掉兄弟元素的狀態。
這裡用 hover 觸發,實務上更建議改成 click:滑過就切換在觸控裝置上完全不可用,也容易誤觸。另外 $("div") 選的是全頁所有 div,頁面結構一變就會錯位,收斂成 $('.panel') 之類的明確選擇器會穩健很多。
最後那個 input 示範的是 placeholder 的純手寫做法,用 onfocus/onblur 切換提示文字。HTML5 已有原生 placeholder 屬性,新專案直接用原生就好。