DIV CSS 佈局教程網

163 AJAX Tab 選單元件
編輯:AJAX基礎知識     

以下為仿 163 風格的 AJAX Tab 元件原始碼,支援以滑鼠延遲感應切換分頁,並能透過 Ajax 動態載入各分頁的內容。

版本更新紀錄

  • 2006.10.18:新增滑鼠延遲感應特性。
  • 2006.10.11:修正 IE5.0 的 undefined 未定義錯誤,並加入腳本錯誤屏蔽。
  • 2006.10.8:A 標籤的 href 屬性保留原有 HTML 功能,另新增 urn 屬性作為 Ajax Load 的路徑。

程式碼

// 163 AJAX Tab
// update 2006.10.18
var Browser = new Object();
Browser.isMozilla = (typeof document.implementation != 'undefined') && (typeof document.implementation.createDocument != 'undefined') && (typeof HTMLDocument!='undefined');
Browser.isIE = window.ActiveXObject ? true : false;
Browser.isFirefox = (navigator.userAgent.toLowerCase().indexOf("firefox")!=-1);
Browser.isOpera = (navigator.userAgent.toLowerCase().indexOf("opera")!=-1);
if (Browser.isFirefox) { extendEventObject(); }
function extendEventObject() {
  Event.prototype.__defineGetter__("srcElement", function () {
    var node = this.target;
    while (node.nodeType != 1) node = node.parentNode;
    return node;
  });
  // 另定義 fromElement、toElement getter 以補齊 Firefox 的事件屬性
}
function IsChild(cNode,pNode){ while(cNode!=null){ cNode=cNode.parentNode; if(cNode==pNode) return true; } return false; }
var ajccache=new Object();
var waitInterval;
var tempref;
var MouseDelayTime=150;//滑鼠感應延遲 150 毫秒
function getTBprefixName(str,sta){ /* 依 active/normal/over 狀態整理 className 前綴 */ }
function startajaxtabs(){ /* 遍歷指定 ul 的第一層 li,為每個分頁掛上 setActive / LoadTab / onmouseover / onmouseout */ }
function getXmlhttp() { /* 依瀏覽器建立 XMLHTTP 物件 */ }
function loadAJAXTab(url,contentid){ /* 若無快取則以 GET 抓取後存入 ajccache,否則直接套用快取內容 */ }
window.onerror=function(){return true}

元件設計重點

  • 跨瀏覽器事件補丁:針對 Firefox 以 __defineGetter__ 擴充 Event 物件,補上 srcElement、fromElement、toElement 等 IE 慣用屬性,讓事件處理能一致運作。
  • 事件冒泡過濾:IsChild() 用來判斷事件來源是否為子元素,避免滑過分頁內的小元素時誤觸切換。
  • 滑鼠延遲感應:onmouseover 時以 setTimeout(MouseDelayTime)延遲觸發 LoadTab,onmouseout 則 clearTimeout 取消,避免快速滑過時頻繁切換。
  • 狀態與快取:setActive 切換 active/normal 的 className;LoadTab 負責切換並載入內容;ajccache 以 url 為鍵快取已載入的內容,二次切換時直接取用,減少請求。
  • urn 與 rel 屬性:連結以 urn 指定 Ajax 載入路徑、以 rel 指定要填充的目標容器 id;href 仍保留原本的 HTML 行為,做到「有 Ajax 用 Ajax、無 Ajax 也能點」的降級效果。

更具體的使用方式,可參考 www.163.com 的實際應用。

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