DIV CSS 佈局教程網

原生 JavaScript 實作元素拖曳:不用任何函式庫
編輯:關於JavaScript     

拖曳功能乍看神祕,其實核心只有三個滑鼠事件。本文用原生 JavaScript 實作一個可拖動的 div,並做適度封裝與瀏覽器相容處理。

思路

1. 先改變被拖曳元素的定位屬性,關鍵是 position: absolute;
2. 捕捉 mousedown、mousemove、mouseup 三個事件;
3. mousedown 時記錄滑鼠在元素內的相對位置 _x、_y;
4. mousemove 時透過改變 top 與 left 移動元素;
5. mouseup 時解除監聽,結束拖曳。

第 3 步是關鍵:記錄的是「滑鼠座標減去元素左上角座標」的差值,這樣拖曳時元素才不會突然跳到滑鼠正下方,造成「抓頭」的錯位感。

完整程式碼

<!DOCTYPE html>
<html>
<head>
<title>draggable div</title>
<style type="text/css">
  body{ margin: 0; padding: 0; background-color: #fff; }
  #drag_div{
    width: 150px; height: 150px; padding: 10px; margin: 10px;
    background-color: #66dd33; cursor: move;
  }
</style>
</head>
<body>
<div id="drag_div"></div>
<script type="text/javascript">
function Drag () {
  this.initialize.apply(this, arguments);
}

Drag.prototype = {
  initialize : function (element, options) {
    this.element = this.$(element);   // 被拖曳的物件
    this._x = this._y = 0;            // 滑鼠在元素中的位置
    this._moveDrag = this.bind(this, this.moveDrag);
    this._stopDrag = this.bind(this, this.stopDrag);
    this.setOptions(options);
    this.handle = this.$(this.options.handle); // 拖曳的「把」可與被拖曳物件不同
    this.onStart = this.options.onStart;
    this.onMove = this.options.onMove;
    this.onStop = this.options.onStop;
    this.handle.style.cursor = "move";
    this.changeLayout();
    this.addHandler(this.handle, "mousedown", this.bind(this, this.startDrag));
  },

  // 改變被拖曳物件的定位屬性
  changeLayout : function () {
    this.element.style.top = this.element.offsetTop + "px";
    this.element.style.left = this.element.offsetLeft + "px";
    this.element.style.position = "absolute";
    this.element.style.margin = "0";
  },

  startDrag : function (event) {
    var event = event || window.event;
    this._x = event.clientX - this.element.offsetLeft;
    this._y = event.clientY - this.element.offsetTop;
    this.addHandler(document, "mousemove", this._moveDrag);
    this.addHandler(document, "mouseup", this._stopDrag);
    this.preventDefault(event);
    this.handle.setCapture && this.handle.setCapture();
    this.onStart();
  },

  moveDrag : function (event) {
    var event = this.getEvent(event);
    var iTop = event.clientY - this._y;
    var iLeft = event.clientX - this._x;
    this.element.style.top = iTop + "px";
    this.element.style.left = iLeft + "px";
    this.onMove();
  },

  stopDrag : function () {
    this.removeHandler(document, "mousemove", this._moveDrag);
    this.removeHandler(document, "mouseup", this._stopDrag);
    this.handle.releaseCapture && this.handle.releaseCapture();
    this.onStop();
  },

  setOptions : function (options) {
    this.options = {
      handle: this.element,          // 事件來源物件
      onStart : function () {},      // 開始時的回呼
      onMove  : function () {},      // 拖曳中的回呼
      onStop  : function () {}       // 停止時的回呼
    };
    for(var p in options){
      this.options[p] = options[p];
    }
  },

  $ : function (id) {
    return typeof id === "string" ? document.getElementById(id) : id;
  },

  addHandler : function (element, eventType, handler) {
    if(element.addEventListener){
      return element.addEventListener(eventType, handler, false);
    }else{
      return element.attachEvent("on" + eventType, handler);
    }
  },

  removeHandler : function (element, eventType, handler) {
    if(element.removeEventListener){
      return element.removeEventListener(eventType, handler, false);
    }else{
      return element.detachEvent("on" + eventType, handler);
    }
  },

  getEvent: function (event) { return event || window.event; },

  preventDefault: function (event) {
    if(event.preventDefault){ event.preventDefault(); }
    else{ event.returnValue = false; }
  },

  bind : function (obj, handler) {
    return function () { return handler.apply(obj, arguments); };
  }
};

window.onload = function () {
  var drag_div = document.getElementById("drag_div");
  new Drag(drag_div, { handle: drag_div });
};
</script>
</body>
</html>

實務上要補上的細節

1. 邊界限制。目前元素可以被拖出視窗外,通常需要在 moveDrag 中把 iTop、iLeft 夾在 0 與「視窗寬高減去元素寬高」之間。
2. 拖曳時不要選取到文字。除了 preventDefault,也建議在拖曳期間幫 body 加上 user-select: none。
3. 滑鼠游標移出視窗會導致拖曳卡住。IE 的 setCapture 就是為了解決這個問題;現代瀏覽器可用 pointer events 搭配 setPointerCapture,一次解決滑鼠、觸控與手寫筆。
4. 觸控裝置需要另外處理。把 mousedown/mousemove/mouseup 換成 touchstart/touchmove/touchend,或在能力支援時直接使用 Pointer Events。
5. 建議加上 html5 drag-and-drop 的替代評估。若需求是「把 A 拖進 B 容器中」,原生 draggable 屬性搭配 dragstart/dragover/drop 會比手工算座標簡單得多;而自製方案則在「自由移動位置」這類需求上更合適。

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