DIV CSS 佈局教程網

工作實作:一個可限制移動範圍的 JS 拖曳元件
編輯:關於JavaScript     

這是工作中實際寫的一個拖曳元件。特色是可以用參數限制移動的最大範圍,並把「矯正呼叫者」這個常見問題獨立成一個工具函式。

使用方法

/*
 * var d = new Drag({ id: 'dragPannel', maxLeft: 500, maxTop: 200 });
 * d.ready();
 *
 * 請注意:拖動對象的 left 和 top 樣式必須寫在其 style 屬性裡邊
 */

最後那句提醒很重要:元件的內部邏輯直接讀寫 moveTarget.style.left,若元素的 left / top 來自 CSS class 而非 inline style,讀到的會是空字串,parseInt 之後變 NaN,整個拖曳就失效了。

核心工具:repairCaller

// 矯正調用者:將 fn 作為 newObj 的方法調用
function repairCaller(newObj, fn) {
  return function () {
    return fn.apply(newObj, arguments);
  };
}

這個函式解決的是「綁定事件時 this 指向錯誤」的經典問題。當你寫 document.onmousedown = this.down 時,事件觸發後 this 會是 document 而不是 Drag 實例。repairCaller 回傳一個包裹函式,強制把 this 固定為 newObj——這就是 Function.prototype.bind 的手工實作。

建構函式

function Drag(config) {
  this.moveTarget = T.dom.get(config.id);
  this.startLeft = parseInt(this.moveTarget.style.left);   // 拖動開始時的 left
  this.startTop = parseInt(this.moveTarget.style.top);     // 拖動開始時的 top
  this.startClientX = this.startLeft;                      // 拖動開始時的 clientX
  this.startClientY = this.startTop;

  // 元素可移動的最大範圍
  this.MAX_LEFT = config.maxLeft || document.documentElement.clientWidth - this.moveTarget.offsetWidth;
  this.MAX_TOP = config.maxTop || document.documentElement.clientHeight - this.moveTarget.offsetHeight;

  this.lock = true;   // 是否鎖定(true 表示不拖動)
}

用 || 提供預設值是很常見的寫法,但要注意:若傳入 0,會被當成 falsy 而改用預設值。若要允許「完全不能移動」的設定,必須改成 config.maxLeft !== undefined ? config.maxLeft : 預設值。

事件綁定

Drag.prototype.ready = function () {
  T.bind(document, "mousedown", repairCaller(this, this.down));
  T.bind(document, "mousemove", repairCaller(this, this.move));
  T.bind(document, "mouseup",   repairCaller(this, this.stop));
};

把 mousemove 與 mouseup 綁在 document 而非元素上,是為了讓拖曳過程中即使滑鼠移出元素範圍仍能持續追蹤。這是拖曳元件的標準做法。

拖曳三階段

Drag.prototype.down = function () {
  var event = T.event.getEvent(arguments[0]),
      target = T.event.getTarget(event);
  if (target == this.moveTarget) {
    this.lock = false;
    // 記錄拖動起點的各項座標
    this.startLeft = parseInt(this.moveTarget.style.left);
    this.startTop = parseInt(this.moveTarget.style.top);
    this.startClientX = event.clientX;
    this.startClientY = event.clientY;
  }
};

Drag.prototype.move = function () {
  if (this.lock) return;
  var event = T.event.getEvent(arguments[0]),
      target = T.event.getTarget(event);

  if (target == this.moveTarget) {
    var realLeft = this.startLeft + event.clientX - this.startClientX,
        realTop  = this.startTop  + event.clientY - this.startClientY,
        rightLeft, rightTop;

    // 夾在 0 與最大值之間
    rightLeft = realLeft > this.MAX_LEFT ? this.MAX_LEFT : (realLeft > 0 ? realLeft : 0);
    rightTop  = realTop  > this.MAX_TOP  ? this.MAX_TOP  : (realTop  > 0 ? realTop  : 0);

    this.moveTarget.style.left = rightLeft + "px";
    this.moveTarget.style.top  = rightTop  + "px";
  } else {
    this.lock = true;    // 滑鼠離開目標就暫停
  }
};

Drag.prototype.stop = function () { this.lock = true; };

位移計算用的是「起點 + 位移差」而非直接取 clientX,這樣即使元素原本不在 (0,0),拖曳也不會跳位。

範圍夾制那段巢狀三元運算子可讀性不佳,等價的寫法更清楚:

rightLeft = Math.min(Math.max(realLeft, 0), this.MAX_LEFT);
rightTop  = Math.min(Math.max(realTop, 0), this.MAX_TOP);

後記:寫作過程中要特别注意的三點

  1. 拖曳層的 position、left 和 top 必須寫在 style 裡(inline style),否則讀不到值。
  2. 移動過程中設定 left 和 top 要帶單位,否則在標準模式下不起作用。
  3. 多層 div 嵌套時需要給父 div 加 overflow: hidden,避免子元素溢出造成版面錯亂。

這個元件可以怎麼改進

  • 用 bind 取代 repairCaller:T.bind(document, 'mousedown', this.down.bind(this)),標準 API 已內建這個能力。
  • 補上 mousedown 之外的入口:目前只有滑鼠完全落在 moveTarget 上才會啟動,若元素內有子節點,target 會是子節點而非 moveTarget,導致按在子元素上拖不動。應改用 moveTarget.contains(target) 判斷。
  • 不支援觸控:行動裝置需要 touchstart / touchmove / touchend,或改用 Pointer Events 一次搞定。
  • 缺少邊界回調:實務上常需要知道「拖到邊界了」或「放開了」以觸發對齊、儲存位置等行為,可加上 onBound / onDrop 回呼。
  • 每次 move 都讀寫 style:可考慮用 transform: translate() 取代 left/top,避免觸發 layout,效能更好且能交給 GPU 合成。

最後一點尤其值得做:transform 只在合成階段處理,不會引起 reflow,在低端裝置上手感差異明顯。

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