简单灵活的jquery的tab选项卡插件

/*
 * ====== 功能简单的选项卡插件 =====
 *  author: Jim
 *      QQ: 307083215
 * version: 3.5 | 2013.12.26
 * =================================
*/

/*---------------------------------
使用示例:

$(".tab").tab({
    card: ".tab-card",
    panel: ".tab-panel",
    highlight: "tab-curCard",    // 注意:类名不带"."

    // 切换成功后执行回调函数, 参数:当前的pannel 和 它在同辈中的索引位置
    callback: function(panel, index){ 

        //这里的this指向 .tab对象

        var img = panel.find('img');
        var src = img.attr('src'),
            source = img.data('src');

        src !== source && img.attr('src', source);

        // do more... 

    }
});

--------------------------------------*/

;(function($){ 


$.fn.tab = function(options){

    var settings = $.extend({
        card: ".tab-card",
        panel: ".tab-panel",
        eType: "mouseover",
        highlight: "tab-curCard",
        speed: 0,
        callback: function (curPanel, index, curCard) { }
    }, options || {});

    this.each(function(){
            var tab   = $(this),
                card  = $(settings.card).filter(function(i){
                    return !!$(this).closest(tab).length;
                }),
                panel = $(settings.panel).filter(function(i){
                    return !!$(this).closest(tab).length;
                }),
                done  = true;    //  切换完成与否


            card[settings.eType](function(){

                    if ( !done || $(this).hasClass(settings.highlight) ) 
                        return;

                    tab.trigger('tabChange', $(this).index());
            });

            tab.on('tabChange', function(e, i){    // 自定义事件

                done = false;

                var curCard = card.eq(i),
                    curPanel = panel.eq(i);

                card.filter('.' + settings.highlight).removeClass(settings.highlight);
                curCard.addClass(settings.highlight);

                panel.filter(':visible').fadeOut(settings.speed, function(){

                    curPanel.fadeIn(settings.speed, function(){
                        settings.callback.apply(tab, [curPanel, i, curCard]);
                        done = true;
                    });

                });
            });
    });

    return this;
};

})(jQuery);

//推荐的html结构
// <div class="tab">
//       <ul class="tab-nav">
//           <li class="tab-card tab-curCard"><a href="javascript:;">card1</a></li>
//           <li class="tab-card"><a href="javascript:;">card2</a></li>
//           <li class="tab-card"><a href="javascript:;">card3</a></li>
//       </ul>
//       <div class="tab-cont">
//           <div class="tab-panel" style="display: block;">panel1</div>
//           <div class="tab-panel" style="display: none;">panel2</div>
//           <div class="tab-panel" style="display: none;">panel3</div>
//       </div>
// </div>

 

posted @ 2013-12-26 23:55  MyNameIsJim  阅读(336)  评论(0编辑  收藏  举报