DIV CSS 佈局教程網

純原生 JavaScript 打造自動輪播 Tab 選項卡:逐行拆解
編輯:關於JavaScript     

選項卡是網頁裡最常見的元件之一,一般要靠滑鼠點擊或移入才會切換。本文要做的更進一步:讓選項卡具備自動輪播能力,滑鼠移入時暫停、移出後繼續,並且把整個功能封裝成一個可重複使用的建構函式。

完整程式碼

<html>
<head>
<meta charset="utf-8">
<title>tab切換</title>
<style type="text/css">
body,h2,p{ margin:0px; padding:0px; }
ul,li{ margin:0px; padding:0px; float:left; list-style-type:none; }
body{font-size:12px;}
.box{ width:722px; height:99px; margin:10px auto; border:1px solid #dedede; }
.list{ width:711px; height:22px; float:left; padding:4px 0 0 9px; border-top:1px solid #fff; border-left:1px solid #fff; border-right:1px solid #fff; }
.list li{ width:74px; height:22px; float:left; cursor:pointer; color:#656565; line-height:22px; text-align:center; }
.list li.hove{ width:72px; height:20px; color:#fc6703; line-height:20px; border-top:1px solid #dedede; border-left:1px solid #dedede; border-right:1px solid #dedede; border-bottom:1px solid #fff; background:#fff; }
.content{ width:722px; height:72px; float:left; display:none; }
</style>
<script>
function $(id){ return typeof id === "string" ? document.getElementById(id) : id; }
function $$(oParent, elem){ return (oParent || document).getElementsByTagName(elem); }
function $$$(oParent, sClass){
  var aElem = $$(oParent, '*');
  var aClass = [];
  var index = 0;
  for(index=0;index<aElem.length;index++){
    if(aElem[index].className == sClass){ aClass.push(aElem[index]); }
  }
  return aClass;
}
function addEvent(oElm, strEvent, fuc) {
  oElm.addEventListener ? oElm.addEventListener(strEvent,fuc,false) : oElm.attachEvent('on'+strEvent,fuc);
};
function Tab(){ this.initialize.apply(this, arguments); }
Object.extend = function(destination, source) {
  for (var property in source) { destination[property] = source[property]; }
  return destination;
};
Tab.prototype = {
  initialize : function(obj, dis, content, onEnd, eq){
    this.obj = $(obj);
    this.oList = $$$(this.obj, 'list')[0];
    this.aCont = $$$(this.obj, content);
    this.oUl = $$(this.oList, 'ul')[0];
    this.aLi = this.oUl.children;
    this.timer = null;
    eq ? (this.aLi.length < eq ? eq = 0 : eq) : eq = 0;
    this.oEve(onEnd);
    this.onEnd.method == 'mouseover' ? this.method = "mouseover" : this.method = "click";
    this.onEnd.autoplay == 'stop' ? this.autoplay = "stop" : this.autoplay = "play";
    this.aCont[eq].style.display = 'block';
    this.aLi[eq].className = 'hove';
    this.display(dis);
    this.autoPlayTab(eq, dis);
  },
  oEve: function(onEnd){
    this.onEnd = { method: 'mouseover', autoplay: 'stop', };
    Object.extend(this.onEnd, onEnd || {});
  },
  display : function(dis){
    var _this = this;
    var index = iNow = 0;
    for(index=0;index<_this.aLi.length;index++){
      (function(){
        var j = index;
        addEvent(_this.aLi[j], _this.method, function() {
          _this.fnClick(j,dis);
          _this.autoPlayTab(j, dis);
        })
      })()
    }
  },
  autoPlayTab : function(iNow, dis){
    if(this.autoplay == 'play'){
      var _this = this;
      this.iNow = iNow;
      this.obj.onmouseover = function(){ clearInterval(_this.timer); };
      this.obj.onmouseout = function(){ _this.timer = setInterval(playTab,5000); };
      clearInterval(_this.timer);
      _this.timer = setInterval(playTab,5000);
      function playTab(){
        if(_this.iNow == _this.aLi.length) _this.iNow = 0;
        _this.fnClick(_this.iNow, dis)
        _this.iNow++
      }
    }
  },
  fnClick : function(oBtn, dis){
    var index = 0;
    for(index=0;index<this.aLi.length;index++){
      this.aLi[index].className = '';
      this.aCont[index].style.display = 'none';
    }
    this.aLi[oBtn].className = dis;
    this.aCont[oBtn].style.display = 'block';
  }
};
window.onload = function(){
  new Tab("box", 'hove', 'content', { method : 'mouseover', autoplay : 'play' },0);
};
</script>
</head>
<body>
<div id="box" class="box">
  <div class="list">
    <ul>
      <li>div教程</li>
      <li>jquery教程</li>
      <li>css教程</li>
    </ul>
  </div>
  <div class="content">第一塊內容</div>
  <div class="content">第二塊內容</div>
  <div class="content">第三塊內容</div>
</div>
</body>
</html>

逐段拆解實現思路

1. three 個選擇器小工具

$ 模擬 jQuery 的 id 選擇器,傳字串就走 getElementById,否則直接把元素原樣返回。

function $(id){
  return typeof id === "string" ? document.getElementById(id) : id;
}

$$ 用 getElementsByTagName 取得指定父元素底下某標籤的集合。

function $$(oParent, elem){
  return (oParent || document).getElementsByTagName(elem);
}

$$$ 則是自行實作的 class 選擇器:先取出父元素底下所有標籤,再把 className 相符的挑進陣列。

function $$$(oParent, sClass){
  var aElem = $$(oParent, '*');
  var aClass = [];
  var index = 0;
  for(index=0;index<aElem.length;index++){
    if(aElem[index].className == sClass){ aClass.push(aElem[index]); }
  }
  return aClass;
}

2. 事件綁定的跨瀏覽器封裝

function addEvent(oElm, strEvent, fuc) {
  oElm.addEventListener ? oElm.addEventListener(strEvent,fuc,false) : oElm.attachEvent('on'+strEvent,fuc);
}

3. 建構函式與原型

Tab 建構函式本身只負責把參數轉交給 initialize,真正的初始化邏輯全寫在原型上。

function Tab(){ this.initialize.apply(this, arguments); }

Object.extend 負責把來源物件的所有屬性合併進目標物件,後面處理自訂參數時會用到。

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}

4. initialize:五個參數的含義

obj 是容器的 id;dis 是選中狀態的 class 名稱;content 是內容區的 class 名稱;onEnd 是設定物件,用來覆寫互動方式與是否自動播放;eq 則指定預設選中第幾個標籤。

this.obj = $(obj);                        //取得容器元素
this.oList = $$$(this.obj, 'list')[0];    //標題外層 div
this.aCont = $$$(this.obj, content);      //內容元素集合
this.oUl = $$(this.oList, 'ul')[0];       //標題 ul
this.aLi = this.oUl.children;             //所有標題項
this.timer = null;                        //定時器標識

接著處理預設索引與各項狀態,最後觸發事件綁定並啟動自動播放。

eq ? (this.aLi.length < eq ? eq = 0 : eq) : eq = 0;
this.oEve(onEnd);
this.onEnd.method == 'mouseover' ? this.method = "mouseover" : this.method = "click";
this.onEnd.autoplay == 'stop' ? this.autoplay = "stop" : this.autoplay = "play";
this.aCont[eq].style.display = 'block';
this.aLi[eq].className = 'hove';
this.display(dis);
this.autoPlayTab(eq, dis);

5. oEve:合併使用者設定

先準備一份預設設定,若呼叫時有傳入 onEnd 物件就合併進去,否則合併空物件。

oEve: function(onEnd){
  this.onEnd = { method: 'mouseover', autoplay: 'stop', };
  Object.extend(this.onEnd, onEnd || {});
}

6. display:用閉包隔離索引

display : function(dis){
  var _this = this;
  var index = iNow = 0;
  for(index=0;index<_this.aLi.length;index++){
    (function(){
      var j = index;
      addEvent(_this.aLi[j], _this.method, function() {
        _this.fnClick(j,dis);
        _this.autoPlayTab(j, dis);
      })
    })()
  }
}

這裡有兩個關鍵細節。第一,把 this 存成 _this,因為事件處理函式裡的 this 指向的是被點擊的 li 元素,而不是 Tab 的實例。第二,用匿名自執行函式形成閉包,把迴圈當下的 index 凍結成 j,否則所有事件都會共用迴圈結束後的最終值。

7. autoPlayTab:自動輪播的核心

只有當 autoplay 為 play 時才啟動。滑鼠移入容器清除定時器,也就是暫停輪播;移出後重新開啟定時器。

this.obj.onmouseover = function(){ clearInterval(_this.timer); };
this.obj.onmouseout = function(){ _this.timer = setInterval(playTab,5000); };
clearInterval(_this.timer);
_this.timer = setInterval(playTab,5000);

playTab 每次被呼叫就切換到目前索引,索引自增;一旦超出 li 的數量就歸零,重新開始新一輪。

function playTab(){
  if(_this.iNow == _this.aLi.length) _this.iNow = 0;
  _this.fnClick(_this.iNow, dis)
  _this.iNow++
}

8. fnClick:樣式與顯示的切換

先把所有標題的 class 清空、所有內容隱藏,再只讓目前這一項加上選中樣式並顯示對應內容。

fnClick : function(oBtn, dis){
  var index = 0;
  for(index=0;index<this.aLi.length;index++){
    this.aLi[index].className = '';
    this.aCont[index].style.display = 'none';
  }
  this.aLi[oBtn].className = dis;
  this.aCont[oBtn].style.display = 'block';
}

這樣就完成了一個可設定互動方式、可開關自動播放的選項卡元件,實際專案裡只要調整 CSS 與呼叫參數即可套用。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved