亲宝软件园·资讯

展开

自定义jQuery选项卡插件实例

人气:0

复制代码 代码如下:

<!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>

加载全部内容

相关教程
猜你喜欢
用户评论