;(function(){ const Tab=function(tab){ let _this=this; //保存单个 tab 组件 _this.tab=tab; // 默认配置参数 const config=_this.config={ "tab":".tab", // 整个选择器 "triggerType":"mouseover", // 触发类型,可选 click 和 mouseover "effect":"default", // 切换效果,可选 default 和 fade "invoke":1, // 默认显示第几个 tab "auto":false // 是否自动切换,可选 false 和切换时间,单位是毫秒 } // 如果配置参数存在,就扩展掉默认参数 if(_this.getConfig()){ $.extend(config,_this.getConfig()); } // 获取 tab 下的每个 li _this.li=$(config.tab).find(".tab_nav li"); // 获取 tab 下的每块内容 _this.contentItem=$(config.tab).find(".item"); // 判断触发事件,并绑定 if(config.triggerType=="click"){ _this.li.bind(config.triggerType,function(){ _this.invoke($(this)); }); }else if(config.triggerType=="mouseover"||config.triggerType!="click"){ _this.li.mouseover(function(){ _this.invoke($(this)); }); } // 全局定时器 if(config.auto){ _this.time=null; // 定时器 _this.loop=0; // 计数器 _this.autoPlay(); // 鼠标移入内容区域停止自动切换,移出继续 _this.contentItem.hover(function(){ window.clearInterval(_this.time); },function(){ _this.autoPlay(); }); } // 设置默认显示第几个 if(config.invoke>1){ _this.invoke(_this.li.eq(config.invoke-1)); } } Tab.prototype={ // 自动间隔时间切换 autoPlay:function(){ let _this=this, li=this.li, liLength=li.length, config=this.config; this.time=window.setInterval(function(){ _this.loop++; if(_this.loop>=liLength){ _this.loop=0; } li.eq(_this.loop).trigger(config.triggerType); },config.auto); }, // 事件驱动函数 invoke:function(currentTab){ let index=currentTab.index(); // 获取当前选中状态下,li 的索引值 currentTab.addClass("active").siblings().removeClass("active"); // li 选中状态 // 切换对应的内容区域 let effect=this.config.effect; let contentItem=this.contentItem; if(effect=="default"||effect!="fade"){ contentItem.eq(index).css("display","flex").siblings().hide(); }else if(effect=="fade"){ contentItem.parent().css("position","relative"); contentItem.css({"position":"absolute","left":0,"right":0}).eq(index).stop(true,false).fadeIn().siblings().fadeOut(); } // 注意:如果配置了自动切换,则把当前的 loop 值设置为当前的 index if(this.config.auto){ this.loop=index; } }, // 获取配置参数 getConfig:function(){ let config=this.tab; // 判断是否有配置参数,如果没有则返回,使用默认值 if(Object.keys(config).length==0){ return null; }else{ return config; } } } // 注册为jQuery方法 // $.fn.extend({ // tab:function(){ // this.each(function(){ // new Tab($(this)); // }); // return this; // } // }); window.Tab=Tab; })(jQuery);