. 代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>jQuery自定義選項卡插件</title>
<style>
body, ul { padding:0; margin:0; }
li { list-style:none; }
#tabs { zoom:1; }
#tab:after { content:""; display:block; clear:both; }
#tabs li { float:left; padding:10px; color:#FF8900; background:#FFF; cursor:pointer; }
#tabs .active { background:#FF8900; color:#FFF; }
#tabContent { background:#FF8900; color:#FFF; padding:10px; clear:both; }
#tabContent div { display:none; }
#tabContent div.active { display:block; }
</style>
</head>
<body>
<ul id="tabs">
<li data-tab="users">Users</li>
<li data-tab="groups">Groups</li>
</ul>
<div id="tabContent">
<div data-tab="users">Users Content</div>
<div data-tab="groups">Groups Content</div>
</div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
jQuery.fn.tabs = function (control) {
var element = $(this);
var control = $(control);
element.delegate('li', 'click', function () {
// 遍歷選項卡名稱
var tabName = $(this).attr('data-tab');
// 點擊選項卡時觸發自定義事件
element.trigger('change.tabs', tabName);
});
// 綁定到自定義事件
element.bind('change.tabs', function (ev, tabName) {
element.find('li').removeClass('active');
element.find('>[data-tab=' + tabName + ']').addClass('active');
});
element.bind('change.tabs', function (ev, tabName) {
control.find('>[data-tab]').removeClass('active');
control.find('>[data-tab=' + tabName + ']').addClass('active');
});
// 激活第 1 個選項卡
var firstName = element.find('li:first').attr('data-tab');
element.trigger('change.tabs', firstName);
return this;
};
jQuery(function ($) {
$('#tabs').tabs('#tabContent');
$('#tab').bind('change.tabs', function (ev, tabName) {
window.loaction.hash = tabName;
});
$(window).bind('hashchange', function () {
var tabName = window.location.hash.slice(1);
$('#tabs').trigger('change.tabs', tabName);
});
});
</script>
</body>
</html>