DIV CSS 佈局教程網

Draggable Elements:從零打造一個元素拖拽元件
編輯:關於JavaScript     

讀懂現成 JS 庫的源碼很有收穫,但自己動手造一次輪子,理解會深得多。下面從最外層的建構函式開始,逐步拆解一個可用的拖拽元件。

對外介面

最頂層的 DragObject 負責初始化一個拖拽物件,參數用設定物件傳入,風格上接近 ExtJS:

var dragObj = new DragObject({
  el: 'exampleB',                 // 被拖拽的元素 id 或 DOM 物件
  attachEl: 'exampleBHandle',     // 拖拽把手(拖它來帶動 el)
  lowerBound: new Position(0, 0),      // 拖拽範圍下界
  upperBound: new Position(500, 500),  // 拖拽範圍上界
  startCallback: ...,             // 開始拖拽時的回呼
  moveCallback: ...,              // 拖拽過程中的回呼
  endCallback: ...,               // 拖拽結束的回呼
  attachLater: ...                // 是否延後綁定監聽
});

el 是被拖的目標,attachEl 是把手;不傳把手時預設等於 el。lowerBound 與 upperBound 用來限制活動範圍,兩者都是 Position 物件,不傳就不限制。

先封裝座標點 Position

function Position(x, y) {
  this.X = x;
  this.Y = y;
}

Position.prototype = {
  constructor: Position,

  add: function (val) {
    var newPos = new Position(this.X, this.Y);
    if (val) { newPos.X += val.X; newPos.Y += val.Y; }
    return newPos;
  },

  subtract: function (val) {
    var newPos = new Position(this.X, this.Y);
    if (val) { newPos.X -= val.X; newPos.Y -= val.Y; }
    return newPos;
  },

  min: function (val) {
    var newPos = new Position(this.X, this.Y);
    if (val) {
      newPos.X = this.X > val.X ? val.X : this.X;
      newPos.Y = this.Y > val.Y ? val.Y : this.Y;
    }
    return newPos;
  },

  max: function (val) {
    var newPos = new Position(this.X, this.Y);
    if (val) {
      newPos.X = this.X < val.X ? val.X : this.X;
      newPos.Y = this.Y < val.Y ? val.Y : this.Y;
    }
    return newPos;
  },

  bound: function (lower, upper) {
    return this.max(lower).min(upper);
  },

  check: function () {
    var newPos = new Position(this.X, this.Y);
    if (isNaN(newPos.X)) newPos.X = 0;
    if (isNaN(newPos.Y)) newPos.Y = 0;
    return newPos;
  },

  apply: function (el) {
    if (typeof el == 'string') el = document.getElementById(el);
    if (!el) return;
    el.style.left = this.X + 'px';
    el.style.top = this.Y + 'px';
  }
};

這個小物件只做一件事:存一組 x、y。add/subtract 做座標運算並回傳新物件;min/max 逐軸比大小;bound 把座標夾在上下界之間;check 確保數值合法,否則歸零;apply 把結果寫進元素的 style.left 與 style.top。注意每個方法都回傳 Position,因此能像 jQuery 那樣串起來呼叫。

DragObject 主體

function DragObject(cfg) {
  var el            = cfg.el,
      attachEl      = cfg.attachEl,
      lowerBound    = cfg.lowerBound,
      upperBound    = cfg.upperBound,
      startCallback = cfg.startCallback,
      moveCallback  = cfg.moveCallback,
      endCallback   = cfg.endCallback,
      attachLater   = cfg.attachLater;

  if (typeof el == 'string') el = document.getElementById(el);
  if (!el) return;

  // 若上下界傳反了,自動交換
  if (lowerBound != undefined && upperBound != undefined) {
    var tempPos  = lowerBound.min(upperBound);
    upperBound   = lowerBound.max(upperBound);
    lowerBound   = tempPos;
  }

  var cursorStartPos, elementStartPos,
      dragging = false,    // 元素是否正在被拖
      listening = false,   // 是否正在監聽拖拽開始事件
      disposed = false;    // 是否已被清理

  function dragStart(eventObj) {
    if (dragging || !listening || disposed) return;
    dragging = true;
    if (startCallback) startCallback(eventObj, el);

    cursorStartPos  = absoluteCursorPosition(eventObj);
    elementStartPos = new Position(parseInt(getStyle(el, 'left')),
                                   parseInt(getStyle(el, 'top')));
    elementStartPos = elementStartPos.check();

    hookEvent(document, 'mousemove', dragGo);
    hookEvent(document, 'mouseup', dragStopHook);
    return cancelEvent(eventObj);
  }

  function dragGo(e) {
    if (!dragging || disposed) return;
    var newPos = absoluteCursorPosition(e);
    newPos = newPos.add(elementStartPos)
                   .subtract(cursorStartPos)
                   .bound(lowerBound, upperBound);
    newPos.apply(el);
    if (moveCallback) moveCallback(newPos, el);
    return cancelEvent(e);
  }

  function dragStopHook(e) {
    dragStop();
    return cancelEvent(e);
  }

  function dragStop() {
    if (!dragging || disposed) return;
    unhookEvent(document, 'mousemove', dragGo);
    unhookEvent(document, 'mouseup', dragStopHook);
    cursorStartPos  = null;
    elementStartPos = null;
    if (endCallback) endCallback(el);
    dragging = false;
  }

  this.startListening = function () {
    if (listening || disposed) return;
    listening = true;
    hookEvent(attachEl, 'mousedown', dragStart);
  };

  this.stopListening = function (stopCurrentDragging) {
    if (!listening || disposed) return;
    unhookEvent(attachEl, 'mousedown', dragStart);
    listening = false;
    if (stopCurrentDragging && dragging) dragStop();
  };

  this.dispose = function () {
    if (disposed) return;
    this.stopListening(true);
    el = attachEl = lowerBound = upperBound = null;
    startCallback = moveCallback = endCallback = null;
    disposed = true;
  };

  this.isDragging  = function () { return dragging;  };
  this.isListening = function () { return listening; };
  this.isDisposed  = function () { return disposed;  };

  if (typeof attachEl == 'string') attachEl = document.getElementById(attachEl);
  if (!attachEl) attachEl = el;     // 沒配置或找不到,就用 el 本身
  if (!attachLater) this.startListening();
}

幾個關鍵細節

為什麼 mousemove 綁在 document 上? 綁在被拖元素上,一旦游標移速稍快、元素跟不上,就會出現拖到一半失效的情形;綁在 document 上則不受影響。

跨瀏覽器的事件綁定:

function hookEvent(el, eventName, callback) {
  if (typeof el == 'string') el = document.getElementById(el);
  if (!el) return;
  if (el.addEventListener)      el.addEventListener(eventName, callback, false);
  else if (el.attachEvent)      el.attachEvent('on' + eventName, callback);
}

function unhookEvent(el, eventName, callback) {
  if (typeof el == 'string') el = document.getElementById(el);
  if (!el) return;
  if (el.removeEventListener) el.removeEventListener(eventName, callback, false);
  else if (el.detachEvent)    el.detachEvent('on' + eventName, callback);
}

取得游標的頁面絕對座標(要把滾動量算進去):

function absoluteCursorPosition(e) {
  e = e ? e : window.event;
  var x = e.clientX + (document.documentElement || document.body).scrollLeft;
  var y = e.clientY + (document.documentElement || document.body).scrollTop;
  return new Position(x, y);
}

讀取樣式值——不論寫成行內樣式還是外部 CSS,都要能拿到:

function getStyle(el, property) {
  if (typeof el == 'string') el = document.getElementById(el);
  if (!el || !property) return;
  var value = el.style[property];
  if (!value) {
    if (document.defaultView && document.defaultView.getComputedStyle) {
      var css = document.defaultView.getComputedStyle(el, null);
      value = css ? css.getPropertyValue(property) : null;
    } else if (el.currentStyle) {
      value = el.currentStyle[property];
    }
  }
  return value == 'auto' ? '' : value;
}

阻止冒泡與預設行為:

function cancelEvent(e) {
  e = e ? e : window.event;
  if (e.stopPropagation) e.stopPropagation();
  if (e.preventDefault)  e.preventDefault();
  e.cancelBubble = true;
  e.returnValue = false;
  return false;
}

整套設計的骨架其實很單純:mousedown 記錄起點並掛上 document 層的監聽,mousemove 用「游標位移 + 元素初值 − 游標初值」算出新座標並夾在範圍內,mouseup 收拾場景。剩下的 startListening/stopListening/dispose 與三個狀態查詢方法,則負責生命週期管理——這部分通常在真正上 production 時才顯得重要,因為它決定了元件能不能被安全地反覆建立與銷毀。

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