DIV CSS 佈局教程網

JavaScript 實作點擊展開的浮層菜單
編輯:JavaScript綜合知識     

本文示範一個點擊後展開的浮層選單效果。這份程式碼寫得較為完整(也稍嫌繁瑣),主要價值在於展示如何用 clip 屬性搭配定時器做出「逐格展開」的動畫,有興趣的可以研究並簡化它。

樣式:用 clip 控制可視區域

DIV.clTopMenu {
  position: absolute;
  width: 101; height: 150;
  clip: rect(0, 101, 14, 0);   /* 一開始只露出 14px 高 */
  visibility: hidden;
  z-index: 31;
  background-color: #00CCFF;
}
DIV.clTopMenuBottom {
  position: absolute;
  width: 101; height: 3;
  clip: rect(0, 101, 3, 0);
  top: 11;
  background-color: #000099;
  z-index: 2;
}
DIV.clTopMenuText {
  position: absolute;
  width: 91; left: 5; top: 15;
  font-family: "Arial", "Helvetica", "sans-serif";
  font-size: 9pt;
  background-color: #EEEEEE;
  z-index: 1;
  color: #000000;
}

clip: rect(top, right, bottom, left) 定義了一個裁剪矩形,只有落在矩形內的內容才會被畫出來。程式一開始把 bottom 設為 14,所以只露出標題列的高度。

瀏覽器能力偵測

function lib_bwcheck() {
  this.ver = navigator.appVersion;
  this.agent = navigator.userAgent;
  this.dom = document.getElementById ? 1 : 0;
  this.opera5 = this.agent.indexOf("Opera 5") > -1;
  this.ie5 = (this.ver.indexOf("MSIE 5") > -1 && this.dom && !this.opera5) ? 1 : 0;
  this.ie6 = (this.ver.indexOf("MSIE 6") > -1 && this.dom && !this.opera5) ? 1 : 0;
  this.ie4 = (document.all && !this.dom && !this.opera5) ? 1 : 0;
  this.ie = this.ie4 || this.ie5 || this.ie6;
  this.ns6 = (this.dom && parseInt(this.ver) >= 5) ? 1 : 0;
  this.ns4 = (document.layers && !this.dom) ? 1 : 0;
  return this;
}
var bw = new lib_bwcheck();

這段是典型的老派寫法:用 user-agent 字串判斷瀏覽器版本,再依結果選擇不同的 DOM 存取方式(getElementById、document.all、document.layers)。今天應該一律改用功能偵測,例如直接檢查 document.getElementById 是否存在。

封裝菜單物件

function makeNewsMenu(obj, nest) {
  nest = (!nest) ? "" : 'document.' + nest + '.';

  this.css = bw.dom ? document.getElementById(obj).style
           : bw.ie4 ? document.all[obj].style
           : bw.ns4 ? eval(nest + "document.layers." + obj) : 0;

  this.evnt = bw.dom ? document.getElementById(obj)
            : bw.ie4 ? document.all[obj]
            : bw.ns4 ? eval(nest + "document.layers." + obj) : 0;

  this.scrollHeight = bw.ns4 ? this.css.document.height : this.evnt.offsetHeight;

  this.moveIt     = b_moveIt;
  this.bgChange   = b_bgChange;
  this.slideUp    = b_slideUp;
  this.slideDown  = b_slideDown;
  this.clipTo     = b_clipTo;

  this.obj = obj + "Object";
  eval(this.obj + "=this");     // 讓 setTimeout 的字串寫法能找到它
}

最後兩行是理解整份程式的鑰匙。因為下面動畫用的是「字串形式的 setTimeout」,字串中的程式碼在全域作用域被 eval,無法直接看到 this,所以工程師把每個菜單物件都掛到全域並以 obj + "Object" 命名,字串裡就能寫 menuObject0.slideUp(...) 這樣的呼叫。

動畫的核心:slideUp 與 slideDown

function b_slideDown(ystop, moveby, speed, fn, wh) {
  if (!this.slideactive) {
    if (this.y < ystop) {
      this.moveIt(this.x, this.y + 5);
      eval(wh);          // 同步更新 clip 高度
      setTimeout(this.obj + ".slideDown(" + ystop + "," + moveby + "," +
                 speed + ",'" + fn + "','" + wh + "')", speed);
    } else {
      this.slideactive = false;
      this.moveIt(0, ystop);
      eval(fn);          // 動畫結束後的收尾
    }
  }
}

邏輯是:每次把 y 座標往下推 5px,同時更新裁剪區域,然後用 setTimeout 排下一幀;直到 y 達到目標值才停止並執行收尾函式。slideUp 只是把加法換成減法。

這種「字串 setTimeout + eval」的寫法如今應改為閉包:

function slideDown(el, targetY, speed) {
  var y = 0;
  (function step() {
    y += 5;
    el.style.clip = `rect(0, 101, ${y + 3}, 0)`;
    if (y < targetY) { setTimeout(step, speed); }
  }());
}

初始化與事件掛載

function newsMenuInit() {
  oTopMenu = new Array();
  zindex = 10;
  for (i = 0; i <= nNumberOfMenus; i++) {
    oTopMenu[i] = new Array();
    oTopMenu[i][0] = new makeNewsMenu('divTopMenu' + i);
    oTopMenu[i][1] = new makeNewsMenu('divTopMenuBottom' + i, 'divTopMenu' + i);
    oTopMenu[i][2] = new makeNewsMenu('divTopMenuText' + i, 'divTopMenu' + i);

    oTopMenu[i][1].moveIt(0, nImageheight);
    oTopMenu[i][0].clipTo(0, nMwidth, nImageheight + 3, 0);

    if (!nPlace) {
      oTopMenu[i][0].moveIt(i * nMwidth + nFromleft + (i * nPxbetween), nFromtop);
    } else {
      oTopMenu[i][0].moveIt(nFromleft, i * nImageheight + nFromtop + (i * nPxbetween));
      oTopMenu[i][0].css.zIndex = zindex--;
    }
    oTopMenu[i][0].css.visibility = "visible";
  }
}

function topMenu(num) {
  if (oTopMenu[num][1].y == nImageheight) {
    oTopMenu[num][1].slideDown(oTopMenu[num][2].scrollHeight + 20, 10, 40,
      'oTopMenu[' + num + '][0].clipTo(0,nMwidth,oTopMenu[' + num + '][1].y+3,0)',
      'oTopMenu[' + num + '][0].clipTo(0,nMwidth,oTopMenu[' + num + '][1].y+3,0)');
  } else if (oTopMenu[num][1].y == oTopMenu[num][2].scrollHeight + 20) {
    oTopMenu[num][1].slideUp(nImageheight, 10, 40, /* 同上 */);
  }
}

function menuOver(num) { oTopMenu[num][1].bgChange(nBgcolorchangeto); }
function menuOut(num)  { oTopMenu[num][1].bgChange(nBgcolor); }
onload = newsMenuInit;

topMenu 是一個 toggle:目前高度等於標題列高度就展開,等於內容總高就收合。menuOver / menuOut 則負責滑過時的底色變化。

HTML 掛上事件

<div id="divTopMenu0" class="clTopMenu" style="height:170; left:20; top:20">
  <span><a href="#" onMouseOver="menuOver(0)" onMouseOut="menuOut(0)"
        onClick="topMenu(0); return false">點擊展開</a></span>

  <div id="divTopMenuText0" class="clTopMenuText">
    <span>鼠標點擊後層展開JavaScript。</span>
  </div>

  <div id="divTopMenuBottom0" class="clTopMenuBottom"
       style="top:11; height:10"></div>
</div>

如果今天重寫

這個效果的核心創意是「用 clip 做逐幀展開」,觀念上仍然有意思,但實作方式幾乎每一行都可以替換掉:

  • 用 CSS max-height 搭配 transition,或 transform: scaleY(),幾行樣式就能取代整套 slide 邏輯。
  • 用 hidden 屬性與 aria-expanded 管理展開狀態,兼顧無障礙。
  • 用 addEventListener 取代 HTML 內的 onClick、onMouseOver。
  • 移除所有 user-agent 判斷與 eval 字串 setTimeout。
  • 點擊展開的選單應考慮點擊外部關閉與 Esc 鍵關閉,這類互動細節在現代元件中屬於基本配備。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved