DIV CSS 佈局教程網

jQuery 實作 Tab 切換與動態載入的入門範例
編輯:JQuery特效代碼     

Tab 頁籤是常見的介面元件,用 jQuery 實作起來相當直覺。以下分兩個範例,從純切換到動態載入,一步步帶你上手。

一、Tab 效果顯示

<html xmlns="https://www.w3.org/1999/xhtml"><head>
<title>無標題頁</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script src="js/jquery-1.4.2-vsdoc.js" type="text/javascript"></script>
<style>
html{ font-size:12px;}
body{ margin:50px;}
div,ul,li{ margin:0; padding:0;}
#tab{ width:200px; margin-top:20px;}
#tab li{ float:left; height:20px; line-height:20px; border:1px solid #000; list-style:none; padding:3px 6px;}
#tab li.on{ background:#3CF;}
#bd div{ width:198px; border:1px solid #000; height:100px; text-align:center; line-height:100px;background:#3CF;}
</style>
</head>
<body>
<ul id="tab">
<li class="on">登錄</li>
<li>注冊</li>
<div style="clear:both;"></div>
</ul>
<div id="bd">
<div>登錄內容</div>
<div>注冊內容</div>
</div>
<script type="text/javascript">
$(function() {
$("#bd>div:not(:first)").hide(); //把不是第一個的內容隱藏起來
$("#tab li").mouseover(function() { //滑鼠移過 li 時觸發
var index = $("#tab li").index(this);//取得當前索引
$(this).addClass("on").siblings().removeClass("on"); //當前項加上樣式,兄弟項移除樣式
$("#bd>div").eq(index).show().siblings().hide(); //顯示對應索引的內容,隱藏其他
});
});
</script>
</body>
</html>

核心邏輯:滑鼠移過某個頁籤時,先用 index(this) 取得它的索引,再據此切換高亮樣式與對應的內容區塊。

二、Tab 效果搭配動態載入

在切換的基礎上,我們還能動態往頁籤與內容區追加新的元素:

<script type="text/javascript">
$(function() {
$("#bd>div:not(:first)").hide();
$("#tab td").mouseover(function() {
var index = $("#tab td").index(this);
$("#bd>div").eq(index).show().siblings().hide();
});
$("#bd a").click(function() {
var link = $("<td><a href='https://www.baidu.com'>百度</a></td>");
var links = $("<div><a href='https://www.baidu.com'>新內容</a></div>");
$("#tab").append(link); //向頁籤區追加
$("#bd").append(links); //向內容區追加
});
});
</script>

透過 append() 動態插入新的頁籤與內容,再搭配前面的切換邏輯,就能打造出具擴充性的 Tab 介面。

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