DIV CSS 佈局教程網

打造 jQuery 風格的鏈式 API:從批量操作到佇列動畫
編輯:關於JavaScript     

用過 jQuery 的人大概都會懷念它的 API 手感。那種手感其實可以拆成兩個關鍵設計:一是鏈式呼叫且以佇列串行,讓程式碼的閱讀順序等於執行順序;二是基於強力選擇器的批量操作,一次處理一整組元素。本文記錄一個自建 mini 函式庫的過程,示範如何從零做出類似風格。

風格的兩個支柱

鏈式且串行。每個 DOM 方法都回傳自身型別的物件,因此可以一路接下去寫。更重要的是,動畫這類耗時操作會被推進佇列,前一個完成後才執行下一個,而不會全部同時啟動。這消除了大量「回呼裡再嵌回呼」的巢狀結構。

批量操作。jQuery 所有 DOM 操作都依賴選擇器取回的一組元素(俗稱 jq 物件),再對其中每個元素並發執行同一套邏輯。使用者不必自己寫迴圈。

順帶一提,我不建議初學者直接學 jQuery 或其他框架。框架把大量邏輯收進內部,讓你少寫很多程式,也讓你少了一次鍛鍊程式邏輯的機會。框架是用來提升開發效率的,不是用來學 JavaScript 的(研究原始碼除外)。

第一步:建立集合物件

var get = function (ids) {
  var d = document, a = -1;
  this.elements = [];
  if (typeof ids != 'string' && !!ids.length) {
    for (var i = 0; i < ids.length; i++) {
      var id = ids[i], o;
      o = typeof id == 'string' ? d.getElementById(id) : id;
      this.elements.push(o);
    }
  } else {
    while (typeof arguments[++a] == 'string') {
      this.elements.push(d.getElementById(arguments[a]));
    }
  }
}

它接受多個 id 字串或一個 id 陣列,統一收進 elements 陣列。寫法與 jQuery 不完全相同,但精神一致。jQuery 大致長這樣:

jQuery = window.jQuery = window.$ = function (selector, context) {
  return new jQuery.fn.init(selector, context);
};
jQuery.fn = jQuery.prototype = {
  init: function (selector, context) {}
};

第二步:擴充原型方法

get.prototype = {
  each: function () {},
  animate: function () {}
};

第三步:each 作為批量基礎

批量操作離不開遍歷,因此 each 是所有方法的基石:

each: function (fn) {
  for (var i = 0; i < this.elements.length; i++) {
    fn.call(this, this.elements[i]);
  }
  return this;
}

它接受一個函式,把每個元素綁定上去執行,最後回傳 get.prototype。因為 prototype 本身具有「超類」性質,凡是回傳 prototype 物件的方法都能繼續串接下去——鏈式就是這樣成立的。

第四步:animate 與佇列

animate: function (config) {
  if (!this.animQueue) this.animQueue = HR._animQueue = [];
  var a = 0, time, tween, ease, callback;
  while (arguments[++a]) {
    if (typeof arguments[a] == 'number') time = arguments[a];
    if (typeof arguments[a] == 'string') {
      if (/^ease*/.test(arguments[a])) ease = arguments[a];
      else tween = arguments[a];
    }
    if (HR.isFunction(arguments[a])) callback = arguments[a];
  }

  this.animQueue.push({
    config: config, time: time, tween: tween, ease: ease, callback: callback
  });
  if (this.animQueue.length == 1) this.execute(this.animQueue);
  return this;
}

這段程式做了兩件事。第一,把動畫設定推入臨時佇列;只有當佇列中原本沒有項目時(length == 1)才立刻啟動,否則就排隊等待。第二,對 arguments 做型別判斷,讓參數位置可以隨意排列:除了第一個 config 與最後的 callback,時間、tween 名稱、緩動名稱都不必顧及順序,寫起來更自由。

若不建立佇列,即使鏈式語法成立了,各段動畫仍會並行播放,達不到預期的接力效果。這是整份程式最核心的設計。

第五步:execute 核心引擎

execute: function (queue) {
  var _this = this, m = 0, n = 0,
  _anim = function (el, key, from, to, at, tw, ease, cb) {
    var isOP = (key == 'opacity' && !HR.support.opacity), _key = key;
    if (isOP) { to = to * 100; _key = 'filter'; }
    var s = +new Date,
        d = at,
        b = parseFloat(from) || 0,
        c = to - b;

    (function () {
      var t = +new Date - s;
      if (t >= d) {
        n++; t = d;
        el.style[_key] = (isOP ? 'alpha(opacity=' : '')
          + Tween.Linear(t, b, c, d)
          + (key != 'opacity' ? 'px' : '') + (isOP ? ')' : '');
        !!cb && cb.apply(el);
        if (m == n && _this.animQueue.length > 1) {
          _this.animQueue.shift();
          _this.execute(_this.animQueue);
        }
        return;
      }
      el.style[_key] = (isOP ? 'alpha(opacity=' : '')
        + Tween[tw][ease](t, b, c, d)
        + (key != 'opacity' ? 'px' : '') + (isOP ? ')' : '');

      if (!HR.timers[el.id]) HR.timers[el.id] = [];
      HR.timers[el.id].push(setTimeout(arguments.callee, 16));
    })();
  },
  _q = this.animQueue[0];

  return this.each(function (el) {
    for (var k in _q.config) {
      m++;
      _anim(el, k,
        k == 'opacity' && !HR.support.opacity
          ? (HR.getStyle('filter', el) == '' ? 100
             : parseInt(HR.getStyle('filter', el).match(/\d{1,3}/g)[0]))
          : HR.getStyle(k, el),
        _q.config[k],
        typeof _q.time == 'number' ? _q.time : 1000,
        typeof _q.tween == 'string' && !/^ease*/.test(_q.tween) ? _q.tween : 'Quart',
        typeof _q.ease == 'string' && /^ease*/.test(_q.ease) ? _q.ease : 'easeOut',
        _q.callback);
    }
  });
}

真正的位移發生在私有函式 _anim 裡:以時間戳計算進度,每 16 毫秒呼叫一次 setTimeout 更新樣式,相當於手動實作一個約 60fps 的計時器。透明度另有一條分支——舊版 IE 不支援 opacity,必須改用 filter: alpha(opacity=n),因此值要乘以 100 並加上前後括號。m 與 n 兩個計數器用來判斷「本批所有元素的所有屬性都跑完了嗎」,若是則 shift 掉佇列頭並遞迴執行下一段。

第六步:stop 讓動畫可控

stop: function (clearQueue) {
  if (clearQueue) HR._animQueue.length = 0;
  this.each(function (el) {
    if (!!HR.timers[el.id])
      for (var i = 0; i < HR.timers[el.id].length; i++)
        clearTimeout(HR.timers[el.id][i]);
  });
  return this;
}

每個元素的計時器 ID 都收藏在 HR.timers[el.id] 中,stop 時遍歷當前元素清單逐一 clearTimeout。可選參數 clearQueue 用來決定是否連後續排隊的動畫一起丟掉。少了這個方法,整份程式碼的實用性會大打折扣。

緩動函式表

jQuery 只提供 swing 一種緩動,這裡多放幾種演算法,全部集中在 Tween 物件中。參數意義為:t 當前時間、b 起始值、c 變化量、d 總時長。

var Tween = {
  Linear: function (t, b, c, d) { return c * t / d + b; },
  Quad: {
    easeIn: function (t, b, c, d) { return c * (t /= d) * t + b; },
    easeOut: function (t, b, c, d) { return -c * (t /= d) * (t - 2) + b; },
    easeInOut: function (t, b, c, d) {
      if ((t /= d / 2) < 1) return c / 2 * t * t + b;
      return -c / 2 * ((--t) * (t - 2) - 1) + b;
    }
  },
  Cubic: {
    easeIn: function (t, b, c, d) { return c * (t /= d) * t * t + b; },
    easeOut: function (t, b, c, d) { return c * ((t = t / d - 1) * t * t + 1) + b; },
    easeInOut: function (t, b, c, d) {
      if ((t /= d / 2) < 1) return c / 2 * t * t * t + b;
      return c / 2 * ((t -= 2) * t * t + 2) + b;
    }
  },
  Quart: {
    easeIn: function (t, b, c, d) { return c * (t /= d) * t * t * t + b; },
    easeOut: function (t, b, c, d) { return -c * ((t = t / d - 1) * t * t * t - 1) + b; },
    easeInOut: function (t, b, c, d) {
      if ((t /= d / 2) < 1) return c / 2 * t * t * t * t + b;
      return -c / 2 * ((t -= 2) * t * t * t - 2) + b;
    }
  },
  Quint: {
    easeIn: function (t, b, c, d) { return c * (t /= d) * t * t * t * t + b; },
    easeOut: function (t, b, c, d) { return c * ((t = t / d - 1) * t * t * t * t + 1) + b; },
    easeInOut: function (t, b, c, d) {
      if ((t /= d / 2) < 1) return c / 2 * t * t * t * t * t + b;
      return c / 2 * ((t -= 2) * t * t * t * t + 2) + b;
    }
  },
  Sine: {
    easeIn: function (t, b, c, d) { return -c * Math.cos(t / d * (Math.PI / 2)) + c + b; },
    easeOut: function (t, b, c, d) { return c * Math.sin(t / d * (Math.PI / 2)) + b; },
    easeInOut: function (t, b, c, d) { return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b; }
  },
  Expo: {
    easeIn: function (t, b, c, d) { return (t == 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b; },
    easeOut: function (t, b, c, d) { return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b; },
    easeInOut: function (t, b, c, d) {
      if (t == 0) return b;
      if (t == d) return b + c;
      if ((t /= d / 2) < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
      return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;
    }
  },
  Circ: {
    easeIn: function (t, b, c, d) { return -c * (Math.sqrt(1 - (t /= d) * t) - 1) + b; },
    easeOut: function (t, b, c, d) { return c * Math.sqrt(1 - (t = t / d - 1) * t) + b; },
    easeInOut: function (t, b, c, d) {
      if ((t /= d / 2) < 1) return -c / 2 * (Math.sqrt(1 - t * t) - 1) + b;
      return c / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1) + b;
    }
  },
  Elastic: {
    easeIn: function (t, b, c, d, a, p) {
      if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3;
      if (!a || a < Math.abs(c)) { a = c; var s = p / 4; }
      else var s = p / (2 * Math.PI) * Math.asin(c / a);
      return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
    },
    easeOut: function (t, b, c, d, a, p) {
      if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3;
      if (!a || a < Math.abs(c)) { a = c; var s = p / 4; }
      else var s = p / (2 * Math.PI) * Math.asin(c / a);
      return (a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b);
    },
    easeInOut: function (t, b, c, d, a, p) {
      if (t == 0) return b; if ((t /= d / 2) == 2) return b + c; if (!p) p = d * (.3 * 1.5);
      if (!a || a < Math.abs(c)) { a = c; var s = p / 4; }
      else var s = p / (2 * Math.PI) * Math.asin(c / a);
      if (t < 1) return -.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p)) + b;
      return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * d - s) * (2 * Math.PI) / p) * .5 + c + b;
    }
  },
  Back: {
    easeIn: function (t, b, c, d, s) {
      if (s == undefined) s = 1.70158;
      return c * (t /= d) * t * ((s + 1) * t - s) + b;
    },
    easeOut: function (t, b, c, d, s) {
      if (s == undefined) s = 1.70158;
      return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b;
    },
    easeInOut: function (t, b, c, d, s) {
      if (s == undefined) s = 1.70158;
      if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
      return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
    }
  },
  Bounce: {
    easeIn: function (t, b, c, d) { return c - Tween.Bounce.easeOut(d - t, 0, c, d) + b; },
    easeOut: function (t, b, c, d) {
      if ((t /= d) < (1 / 2.75)) {
        return c * (7.5625 * t * t) + b;
      } else if (t < (2 / 2.75)) {
        return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
      } else if (t < (2.5 / 2.75)) {
        return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
      } else {
        return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
      }
    },
    easeInOut: function (t, b, c, d) {
      if (t < d / 2) return Tween.Bounce.easeIn(t * 2, 0, c, d) * .5 + b;
      else return Tween.Bounce.easeOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
    }
  }
};

工具函式與註冊入口

HR.extend(HR, {
  get: function () { return new get(arguments); },
  isFunction: function (o) {
    return typeof (o) == 'function' && (!Function.prototype.call || typeof (o.call) == 'function');
  },
  getStyle: function (p, el) {
    return el.currentStyle ? el.currentStyle[p]
      : document.defaultView.getComputedStyle(el, null).getPropertyValue(p);
  },
  support: (function () {
    try {
      var d = document.createElement('div');
      d.style['display'] = 'none';
      d.innerHTML = '<a style="float:left; opacity:.5;"></a>';
      var a = d.getElementsByTagName('a')[0];
      return { opacity: a.style.opacity === '0.5' };
    } finally { d = null; }
  })(),
  timers: {}
});

support 那段用「建立隱藏元素、寫入樣式、讀回來比對」的手法來做特性偵測,是判斷瀏覽器是否支援 opacity 的經典技巧。HR.timers 則是全域計時器登錄表。

可用的原型方法總表

get.prototype 上掛了 each、setStyle、show、hide、animate、stop、execute。其中 setStyle/show/hide 都是 each 的薄封裝,示範了批量操作如何以極低成本組裝出來:

setStyle: function (p, v) {
  this.each(function (el) { el.style[p] = v; });
  return this;
}

示範一:鏈式停止與移動

注意 onclick 那一行:HR.get('me','you') 一次取兩個元素,.stop() 先清空佇列並停止計時器,.animate({top:100}) 再讓兩個方塊同時往目標位置移動。鏈式與批量在這一行裡同時體現。

示範二:選單展開動畫

這個示範把 height 從 0 動畫到目標值,搭配容器的 overflow: hidden,做出選單展開的效果。原始示範還包含遮罩淡入與文字進場,原理相同。

回顧:這份實作教了我們什麼

從零打造 mini 函式庫,價值不在於取代 jQuery,而在於把「好用」拆解成可理解的成本。鏈式來自「每個方法都回傳 this」這個紀律;批量來自「所有方法都走 each」這個約定;串行來自一個明確的佇列與「全部完成才 shift」的判斷;可控則來自計時器 ID 的集中管理。

這份程式碼也有明顯的時代痕跡:arguments.callee 在嚴格模式下不可用,動畫以 setTimeout 16ms 手動實作(今日應改用 requestAnimationFrame),opacity 的 filter 分支已無必要。但它示範的設計骨架——集合物件、原型擴充、佇列串行、時間驅動更新——至今仍是理解前端函式庫架構的最佳入門路徑。

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