DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> JavaScript入門知識 >> AJAX入門 >> AJAX詳解
仿雅虎、網易風格的 Ajax 標籤導航實作
編輯:AJAX詳解     

經過多次改進,這個標籤導航已經可以直接用在一般網站上。原始碼以 UTF-8 編碼提供;若要改成 GB2312,用記事本打開後另存時選擇相應編碼即可。由於只是標籤導航,所有內容仍會在頻道頁中呈現,因此這裡全部用 Ajax 讀取。

實作思路

雅虎中國風格

  • 單擊觸發
  • <A> 區塊鎖定:a{display:block;height:16px;}(把 A 標籤設為區塊級元素,再定義寬高)
  • 再次單擊時彈出連結:在 <A> 標記的 onclick 事件中,需要讀取時 return false;,否則 return true;
  • Ajax 讀取資料
  • 資料暫存
  • 視窗平滑收合

(由於看不懂雅虎的原始程式,這裡用一些基本程式碼來實作這些功能,效率未必最高,但效果是做得出來的。)

網易風格

  • 滑鼠移入延時觸發:onmouseover 時 var waitInterval = window.setTimeout("func();", 300);,onmouseout 時 clearTimeout(waitInterval);
  • <A> 區塊鎖定、Ajax 讀取資料、資料暫存、視窗平滑收合

其他功能

  • Cookie 記憶上次狀態
  • 顯示最後讀取資料的伺服器時間
  • 滑門技術

線上效果:https://www.lorlo.com/tab.html

JavaScript 程式碼

(Ctrl+A 全選後複製)

function getObject(objectId) {
  if (document.getElementById && document.getElementById(objectId)) {
      // W3C DOM
      return document.getElementById(objectId);
  } else if (document.all && document.all(objectId)) {
      // MSIE 4 DOM
      return document.all(objectId);
  } else if (document.layers && document.layers[objectId]) {
      // NN 4 DOM,注意:找不到巢狀的 layer
      return document.layers[objectId];
  } else {
      return false;
  }
}

var responsecont;
var xmlHttp;
var xH = new Object();
var rqtp = new Object();
var dateStr, dStr;
var requestType;
var etype = 0;
var newsstring;
var ajccache = new Object();
var url;
var MouseDelayTime = 200; // 滑鼠感應延遲
var waitInterval;

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);

function SetCookie(name, value, expires) { // 寫 cookie
  var exp = new Date();
  exp.setTime(exp.getTime() + expires * 60000);
  document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}

function readcookie(name) { // 讀取 cookie
  var oRegex = new RegExp(name + '=([^;]+)', 'i');
  var oMatch = oRegex.exec(document.cookie);
  if (oMatch && oMatch.length > 1) return unescape(oMatch[1]);
  else return '';
}

function CreateXMLHttpRequest() {
  // Mozilla 的 XMLHttpRequest
  if (window.XMLHttpRequest) {
    xmlHttp = new XMLHttpRequest();
  }
  // IE/Windows 的 ActiveX 版本
  else if (window.ActiveXObject) {
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP.3.0");
    } catch (e) {
      try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        newsstring = "<div class='loading'>Loading request content fail, Please try it again later...</div>";
      }
    }
  }
}

function getnews(tagid, x) {
  url = "tab/" + tagid + '_' + x + '.html';
  var url2 = url;
  requestType = tagid;
  if (ajccache[url] == null) {
    var loadstatustext = "<div class='loading'><img src='/School/UploadFiles_7810/201104/20110424233634746.gif' /> Loading request content, please wait...</div>";
    rqtp[tagid] = tagid;
    CreateXMLHttpRequest();
    var hdr = tagid;
    xH[tagid] = xmlHttp;
    if (etype == 1) getObject(requestType + '_cnt').innerHTML = loadstatustext;
    xH[tagid].onreadystatechange = function() {
      // 只在 XMLHttp 顯示「完成」時處理
      if (xH[tagid].readyState == 4) {
        // 只處理 http 200
        if (window.location.href.indexOf("http") == -1 || xH[tagid].status == 200) {
          newsstring = xH[tagid].responseText;
          dateStr = xH[tagid].getResponseHeader("Date");
          dStr = new Date(dateStr);
          SetCookie('dStr', dStr, 10000000);
          // 把內容注入標籤面板
          shownews(rqtp[tagid], newsstring);
          ajccache[url2] = newsstring;
        }
      }
    }
    xH[tagid].open("GET", url, true);
    xH[tagid].setRequestHeader("If-Modified-Since", "0");
    xH[tagid].send(null);
  } else {
    shownews(requestType, ajccache[url]);
  }
}

function shownews(requestType, newsstring) {
  responsecont = getObject(requestType + '_cnt');
  responsecont.innerHTML = newsstring;
  getObject("pdate").innerHTML = dStr;
  if (getObject("alta")) {
    ata(getObject("alta"));
    hideText();
  }
}

function TabNews(tagid, x) {
  var lim = getObject(tagid + "_mn").getElementsByTagName('li');
  var mnt = getObject(tagid + "_mn").getElementsByTagName('li').length;
  if (!mnt) mnt = 4;
  for (var i = 0; i < mnt; i++) {
    if (i == (x - 1)) {
      if (i == 0) {
        lim[i].className = "tabactive1";
      } else {
        lim[i].className = "tabactive2";
        lim[i - 1].getElementsByTagName('a')[0].style.background = "url()";
      }
      lim[i].getElementsByTagName('a')[0].style.background = "url(tab/images/tab_bgs.gif) right -60px no-repeat";
      try {
        getnews(tagid, x);
      } catch (e) {
        alert(e);
      }
    } else {
      lim[i].className = "";
      lim[i].getElementsByTagName('a')[0].style.background = "url(tab/images/tab_bgs.gif) right -88px no-repeat";
    }
  }
}

var idn, tmpa, tmpat;
var aw = "";
var rT;

function aet(tagid, etp) {
  var lis = getObject(tagid + "_mn").getElementsByTagName('li');
  var wts = tagid + "_cnt";
  var wnf = tagid + "info";

  if (readcookie(tagid + "_cntd") == "none") {
    hiddenList(getObject(wts));
    maxh[wts] = readcookie(tagid + "_cnth");
    getObject("pdate").innerText = readcookie("dStr");
  } else {
    if (parseInt(readcookie(wnf)) > 1) TabNews(tagid, readcookie(wnf)); // 回到上次瀏覽的標籤
    else TabNews(tagid, 1);
    if (etp == 1) aw = tagid + readcookie(wnf);
  }

  for (var iy = 0; iy < lis.length; iy++) {
    with (lis[iy]) {
      if (etp == 0) {
        // 滑鼠移入:延時觸發
        lis[iy].onmouseover = function() {
          rT = attributes.getNamedItem('id').value.substring(0, attributes.getNamedItem('id').value.length - 1);
          if (getObject(rT + '_cnt').style.display != "none" && className != "") return;
          idn = parseInt(attributes.getNamedItem('id').value.substring(attributes.getNamedItem('id').value.length - 1, attributes.getNamedItem('id').value.length));
          clearTimeout(waitInterval);
          waitInterval = window.setTimeout("etype=0;TabNews(rT,idn);if(getObject(rT+'_cnt').style.display == 'none')displayList(rT+'_cnt'); SetCookie(rT+'info',idn,10000000);SetCookie(rT+'_cntd','ture',10000000);", MouseDelayTime);
        }
        // 滑鼠移出:取消計時器
        lis[iy].onmouseout = function() {
          if (getObject(rT + '_cnt').style.display != "none" && className != "") return;
          clearTimeout(waitInterval);
        }
      }
      if (etp == 1) {
        // 點擊模式
        lis[iy].onmouseover = function() {
          getElementsByTagName('a')[0].blur();
        }
        lis[iy].onclick = function() {
          idn = parseInt(attributes.getNamedItem('id').value.substring(attributes.getNamedItem('id').value.length - 1, attributes.getNamedItem('id').value.length));
          rT = attributes.getNamedItem('id').value.substring(0, attributes.getNamedItem('id').value.length - 1);
          if (getObject(rT + '_cnt').style.display != "none" && (idn == 1 && (this.className == "tabactive1") || aw == attributes.getNamedItem('id').value)) return true;
          if (getObject(rT + '_cnt').style.display == "none") {
            displayList(rT + '_cnt');
            SetCookie(rT + '_cntd', 'ture', 10000000);
          }
          etype = 1;
          TabNews(rT, idn);
          SetCookie(rT + 'info', idn, 10000000);
          aw = attributes.getNamedItem('id').value;
          getElementsByTagName('a')[0].blur();
          return false;
        }
      }
    }
  }
}

function ata(objid) {
  var as = objid.getElementsByTagName('a');
  for (var i = 0; i < as.length; i++) {
    as[i].target = "_self";
  }
}

function GetUrlParam(paramName) { // 取得 URL 參數
  var oRegex = new RegExp('[?&]' + paramName + '=([^&]+)', 'i');
  var oMatch = oRegex.exec(window.location.search);
  if (oMatch && oMatch.length > 1) return oMatch[1];
  else return '';
}

function hideText() {
  if (document.getElementsByTagName("arkoo:title").length == 0) {
    var upu = GetUrlParam("username");
    var upa = GetUrlParam("articleid");
    getObject("closeit").innerHTML = '<a href="https://cn.arkoo.com/diaryfiles/showpage.aspx?username=' + upu + '&articleid=' + upa + '" target="_blank">查看原文</a> <a href="tab.html" target="_self">×</a>';
  }
}

var maxh = new Object();

// 展開內容框
function displayList(oid) {
  var h = 0;
  var objid = getObject(oid);
  if (isNaN(parseInt(maxh[oid]))) var max_h = 210; // 容器的最大高度
  else var max_h = maxh[oid];
  var anim = function() {
    h += 50; // 每次遞增 50 像素
    if (h >= max_h) {
      objid.style.height = max_h + "px";
      getObject('tab' + objid.attributes.getNamedItem('id').value).style.background = "url(tab/images/tab_bgs.gif) 5px -113px no-repeat";
      if (tt) { window.clearInterval(tt); }
    } else {
      objid.style.display = "block";
      objid.style.height = h + "px";
    }
  }
  var tt = window.setInterval(anim, 2);
}

// 收合內容框
function hiddenList(objid) {
  var h = objid.offsetHeight;
  var anim = function() {
    h -= 50; // 每次遞減 50 像素
    if (h <= 5) {
      objid.style.display = "none";
      getObject('tab' + objid.attributes.getNamedItem('id').value).style.background = "url(tab/images/tab_bgs.gif) -14px -114px no-repeat";
      if (tt) { window.clearInterval(tt); }
    } else {
      objid.style.height = h + "px";
    }
  }
  var tt = window.setInterval(anim, 2);
}

function showClassList(oid) {
  var objid = getObject(oid);
  if (objid.style.display == "none") {
    if (objid.getElementsByTagName("img").length == 0) TabNews(oid.substring(0, oid.indexOf("_")), 1);
    displayList(oid); // 顯示內容框
    SetCookie(oid + 'd', "ture", 10000000);
  } else {
    if (isNaN(parseInt(maxh[oid]))) {
      if (Browser.isFirefox) {
        maxh[oid] = objid.offsetHeight;
      } else {
        maxh[oid] = objid.offsetHeight; // 內容容器的初始高度
      }
    }
    hiddenList(objid); // 隱藏內容框
    SetCookie(oid + 'd', "none", 10000000);
    SetCookie(oid + 'h', maxh[oid], 10000000);
  }
}
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved