基于jQuery的选项卡

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
 5     <title>Example 1</title>
 6     <link rel="stylesheet" href="index.css" />
 7     <script type="text/javascript" src="jquery-1.7.2.min.js"></script>
 8     <script type="text/javascript" src="index.js"></script>
 9     <script type="text/javascript">
10     $(function() {
11         $("#tabs").tabs("#main");
12     });
13     </script>
14 </head>
15 <body>
16     <ul id="tabs">
17         <li data-tab="sect1">Sect1</li>
18         <li data-tab="sect2">Sect2</li>
19         <li data-tab="sect3">Sect3</li>
20         <li data-tab="sect4">Sect4</li>
21         <li data-tab="sect5">Sect5</li>
22     </ul>
23     <div id="main">
24         <div data-tab="sect1">Sect1 content</div>
25         <div data-tab="sect2">Sect2 content</div>
26         <div data-tab="sect3">Sect3 content</div>
27         <div data-tab="sect4">Sect4 content</div>
28         <div data-tab="sect5">Sect5 content</div>
29     </div>
30 </body>
31 </html>

 

 1 #tabs {
 2     list-style: none;
 3     overflow: hidden;
 4 }
 5 
 6 #tabs li {
 7     float: left;
 8     padding: 10px;
 9     cursor: pointer;
10 }
11 
12 #tabs li.active {
13     color: red;
14 }
15 
16 #main div {
17     display: none;
18 }
19 
20 #main .active {
21     display: block;
22 }

 

jQuery.fn.tabs = function(control) {
    var element = $(this);
    control = $(control);

    //Delegate(委派)
    element.delegate("li", "click", function() {
        //遍历选项卡名称
        var tabName = $(this).attr("data-tab");

        //在点击选项卡时触发自定义事件
        element.trigger("change.tabs", tabName);
    });

    //绑定到自定义事件
    element.bind("change.tabs", function(e, tabName) {
        element.find("li").removeClass("active");
        element.find(">[data-tab='" + tabName + "']").addClass("active");
    });

    element.bind("change.tabs", function(e, 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;
};
posted @ 2012-07-30 16:54  小猩猩君  阅读(213)  评论(0编辑  收藏  举报