騰訊首頁的每個新聞欄目都是一個tab選項卡切換,屬於延遲動作的:鼠標hover上去之后200毫秒才會切換,防止了因為瀏覽滑動導致的頁面上選項卡的頻繁切換。仿照這樣的效果,自己寫了一個js插件,實現了低版本瀏覽器IE7-8的兼容,沒有用庫,純js寫的。
難點的話就是如何實現延時動作,我想到的辦法是用setTimeOut函數,期間要遍歷Tabhead中的a節點進行綁定事件,寫了一個很逗的閉包向setTimeOut傳入循環變量。
核心js部分代碼如下:
1 /* 2 * 仿Tencent 選項卡延遲切換 3 * 參數:TabID,Tab標題的選中class,延遲時間 4 * 5 */ 6 7 //為數組對象添加判斷子元素方法 8 Object.prototype.isIn = function(item){ 9 var i = this.length; 10 while (i--) { 11 if ( item === this[i]) { 12 return true; 13 } 14 } 15 return false; 16 }; 17 Object.prototype.getPos = function(item){ 18 var i = this.length; 19 while (i--) { 20 if ( item === this[i]) { 21 return i; 22 } 23 } 24 return -1; 25 }; 26 //TabBar對象 27 var TabBar = function(eId,className,delayTime){ 28 //防止漏寫new導致bug js設計模式里推薦 感覺比較雞肋 29 if(!(this instanceof TabBar)){ 30 return new TabBar(eId,className,delayTime); 31 } 32 //el:Tab組件對應的元素 33 //showNum:當前顯示的Tab子欄序號,從0開始 34 //selectClass:Tab標題欄選中class樣式 35 //delayTime: 鼠標延遲時間 36 //hd,sub數組:tab頭元素和tabSub元素數組 37 this.el = document.getElementById(eId||"tab"); 38 this.showNum = 0; 39 this.selectClass = className || "selected"; 40 this.delayTime = delayTime || 200; 41 this.hd = this.el.getElementsByTagName("div")[0].getElementsByTagName("a"); 42 this.sub = this.el.getElementsByTagName("div")[1].querySelectorAll(".sub_item"); 43 //類初始化最后執行bind函數 44 this.bindListener(); 45 } 46 47 TabBar.prototype.show = function() { 48 //用於顯示當前ShowNum對應的Tab項 49 this.sub[this.showNum].style.display ="block"; 50 }; 51 TabBar.prototype.hide = function() { 52 //用於取消顯示當前ShowNum對應的Tab項 53 (this.sub[this.showNum]).style.display ="none"; 54 }; 55 TabBar.prototype.bindListener = function() { 56 //綁定hover事件 self局部變量傳遞this,addEventListener默認對象為window 57 var self = this; 58 if(this.el.addEventListener == undefined){ 59 //兼容IE7,8 60 var i =0; 61 for( i=0;i<this.hd.length;i++){ 62 this.hd[i].attachEvent("onmouseover",(function(pos){ 63 return function (){ 64 (self.hd[pos]).timer = setTimeout(function(){ 65 self.switchTab(pos); 66 },self.delayTime); 67 } 68 })(i)); 69 this.hd[i].attachEvent("onmouseout",(function(pos){ 70 return function (){ 71 clearTimeout( self.hd[pos].timer ); 72 } 73 })(i)); 74 } 75 } 76 else{ 77 //非IE7,8 addEventListener綁定 78 this.el.addEventListener("mouseover",function(event){ 79 if( self.hd.isIn(event.target) ){ 80 var pos = self.hd.getPos(event.target); 81 (self.hd[pos]).timer = setTimeout(function(){ 82 self.switchTab(pos); 83 },self.delayTime); 84 } 85 }); 86 this.el.addEventListener("mouseout",function(event){ 87 if( self.hd.isIn(event.target) ){ 88 var pos = self.hd.getPos(event.target); 89 clearTimeout( self.hd[pos].timer ); 90 } 91 }); 92 } 93 }; 94 TabBar.prototype.switchTab = function(pos){ 95 //選項卡切換函數 參數:pos,當前Hover的子欄序號,從0開始 96 if( pos !== this.showNum ){ 97 this.hd[this.showNum].className = ""; 98 this.hd[pos].className=this.selectClass; 99 this.hide(); 100 this.showNum = pos; 101 this.show(); 102 } 103 }; 104 //Tab實例化 105 var LeeTab =new TabBar("tab");
demo地址:Tab切換演示
恩,就是這樣。