自定义jQuery选项卡插件实例
代码如下:
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "https://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 p { display:none; }
#tabcontent p.active { display:block; }
</style>
</head>
<body>
<ul id="tabs">
<li data-tab="users">users</li>
<li data-tab="groups">groups</li>
</ul>
<p id="tabcontent">
<p data-tab="users">users content</p>
<p data-tab="groups">groups content</p>
</p>
<script src="https://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>