您的位置:首页 > Web前端 > JavaScript

[javascript]switchTab:仿腾讯首页Tab栏切换js插件

2014-11-17 15:25 691 查看
  腾讯首页的每个新闻栏目都是一个tab选项卡切换,属于延迟动作的:鼠标hover上去之后200毫秒才会切换,防止了因为浏览滑动导致的页面上选项卡的频繁切换。仿照这样的效果,自己写了一个js插件,实现了低版本浏览器IE7-8的兼容,没有用库,纯js写的。

  难点的话就是如何实现延时动作,我想到的办法是用setTimeOut函数,期间要遍历Tabhead中的a节点进行绑定事件,写了一个很逗的闭包向setTimeOut传入循环变量。

  核心js部分代码如下:

/*
*   仿Tencent 选项卡延迟切换
*   参数:TabID,Tab标题的选中class,延迟时间
*
*/

//为数组对象添加判断子元素方法
Object.prototype.isIn = function(item){
var i = this.length;
while (i--) {
if ( item === this[i]) {
return true;
}
}
return false;
};
Object.prototype.getPos = function(item){
var i = this.length;
while (i--) {
if ( item === this[i]) {
return i;
}
}
return -1;
};
//TabBar对象
var TabBar = function(eId,className,delayTime){
//防止漏写new导致bug  js设计模式里推荐 感觉比较鸡肋
if(!(this instanceof TabBar)){
return new TabBar(eId,className,delayTime);
}
//el:Tab组件对应的元素
//showNum:当前显示的Tab子栏序号,从0开始
//selectClass:Tab标题栏选中class样式
//delayTime: 鼠标延迟时间
//hd,sub数组:tab头元素和tabSub元素数组
this.el = document.getElementById(eId||"tab");
this.showNum = 0;
this.selectClass = className || "selected";
this.delayTime = delayTime || 200;
this.hd = this.el.getElementsByTagName("div")[0].getElementsByTagName("a");
this.sub = this.el.getElementsByTagName("div")[1].querySelectorAll(".sub_item");
//类初始化最后执行bind函数
this.bindListener();
}

TabBar.prototype.show = function() {
//用于显示当前ShowNum对应的Tab项
this.sub[this.showNum].style.display ="block";
};
TabBar.prototype.hide = function() {
//用于取消显示当前ShowNum对应的Tab项
(this.sub[this.showNum]).style.display ="none";
};
TabBar.prototype.bindListener = function() {
//绑定hover事件 self局部变量传递this,addEventListener默认对象为window
var self = this;
if(this.el.addEventListener == undefined){
//兼容IE7,8
var i =0;
for( i=0;i<this.hd.length;i++){
this.hd[i].attachEvent("onmouseover",(function(pos){
return function (){
(self.hd[pos]).timer = setTimeout(function(){
self.switchTab(pos);
},self.delayTime);
}
})(i));
this.hd[i].attachEvent("onmouseout",(function(pos){
return function (){
clearTimeout( self.hd[pos].timer );
}
})(i));
}
}
else{
//非IE7,8 addEventListener绑定
this.el.addEventListener("mouseover",function(event){
if( self.hd.isIn(event.target) ){
var pos = self.hd.getPos(event.target);
(self.hd[pos]).timer = setTimeout(function(){
self.switchTab(pos);
},self.delayTime);
}
});
this.el.addEventListener("mouseout",function(event){
if( self.hd.isIn(event.target) ){
var pos = self.hd.getPos(event.target);
clearTimeout( self.hd[pos].timer );
}
});
}
};
TabBar.prototype.switchTab = function(pos){
//选项卡切换函数 参数:pos,当前Hover的子栏序号,从0开始
if( pos !== this.showNum ){
this.hd[this.showNum].className = "";
this.hd[pos].className=this.selectClass;
this.hide();
this.showNum = pos;
this.show();
}
};
//Tab实例化
var LeeTab =new TabBar("tab");


  demo地址:Tab切换演示

  恩,就是这样。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: