萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

純 JavaScript 實現簡易拖拽效果:從基礎邏輯到面向對象封裝

前言

在前端開發中,拖拽交互是常見需求。雖然 jQuery UI 的 draggable 成熟穩定,但深入理解原生 JS 實現原理,有助於靈活應對定製化場景。本文將從零開始,逐步講解如何用純 JavaScript 實現一個簡單且可複用的拖拽插件。

一、基礎結構:HTML 與 CSS

首先準備一個可拖拽的方塊元素,並設置基本樣式:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>簡易拖拽示例</title>
<style>
* { margin: 0; padding: 0; }
#dragBox {
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: #e74c3c;
  cursor: move;
  user-select: none; /* 防止拖拽時選中文字 */
}
</style>
</head>
<body>
<div id="dragBox"></div>
</body>
</html>

拖拽元素初始狀態

二、核心邏輯:事件監聽與座標計算

拖拽的核心在於三個階段:按下(mousedown)、移動(mousemove)、釋放。關鍵點是計算鼠標相對於元素左上角的偏移量,並在移動時實時更新元素位置。

<script>
window.onload = function () {
  var box = document.getElementById('dragBox');
  
  box.onmousedown = function (e) {
    e = e || window.event;
    // 計算鼠標按下時,相對於元素左上角的偏移
    var offsetX = e.clientX - box.offsetLeft;
    var offsetY = e.clientY - box.offsetTop;
    
    document.onmousemove = function (e) {
      e = e || window.event;
      // 實時計算新位置
      var left = e.clientX - offsetX;
      var top  = e.clientY - offsetY;
      
      // 邊界限制:防止拖出視窗
      var maxLeft = document.documentElement.clientWidth - box.offsetWidth;
      var maxTop  = document.documentElement.clientHeight - box.offsetHeight;
      left = Math.max(0, Math.min(left, maxLeft));
      top  = Math.max(0, Math.min(top,  maxTop));
      
      box.style.left = left + 'px';
      box.style.top  = top  + 'px';
    };
    
    document.onmouseup = function () {
      document.onmousemove = null;
      document.onmouseup   = null;
    };
    
    return false; // 取消默認行為(如文字選中)
  };
};
</script>

三、進階封裝:面向對象的 Drag 類

為了支援多個元素同時拖拽,將邏輯封裝為可複用的類:

function Drag(id) {
  this.el = document.getElementById(id);
  if (!this.el) return;
  
  this.el.style.position = 'absolute';
  this.el.style.cursor   = 'move';
  this.offsetX = 0;
  this.offsetY = 0;
  
  var self = this;
  
  this.el.onmousedown = function (e) {
    self._onMouseDown(e);
  };
}

Drag.prototype._onMouseDown = function (e) {
  e = e || window.event;
  this.offsetX = e.clientX - this.el.offsetLeft;
  this.offsetY = e.clientY - this.el.offsetTop;
  
  var self = this;
  document.onmousemove = function (e) { self._onMouseMove(e); };
  document.onmouseup   = function ()   { self._onMouseUp();   };
};

Drag.prototype._onMouseMove = function (e) {
  e = e || window.event;
  var left = e.clientX - this.offsetX;
  var top  = e.clientY - this.offsetY;
  
  var maxLeft = document.documentElement.clientWidth  - this.el.offsetWidth;
  var maxTop  = document.documentElement.clientHeight - this.el.offsetHeight;
  left = Math.max(0, Math.min(left, maxLeft));
  top  = Math.max(0, Math.min(top,  maxTop));
  
  this.el.style.left = left + 'px';
  this.el.style.top  = top  + 'px';
};

Drag.prototype._onMouseUp = function () {
  document.onmousemove = null;
  document.onmouseup   = null;
};

四、使用示例

實例化多個拖拽元素:

<style>
#box1 { width: 100px; height: 100px; background: #e74c3c; }
#box2 { width: 100px; height: 100px; background: #f1c40f; }
</style>
<div id="box1"></div>
<div id="box2"></div>

<script>
window.onload = function () {
  new Drag('box1');
  new Drag('box2');
};
</script>

多元素拖拽效果演示

五、總結與擴展建議

  • 本實現採用 document 級別綁定移動/釋放事件,避免鼠標移出元素導致事件丟失。
  • 邊界檢測使用 Math.min/max 簡化邏輯,比多重 if/else 更優雅。
  • 實際項目中可考慮加入:拖拽回調、吸附對齊、觸屏支援(touchstart/move/end)、請求動畫幀(requestAnimationFrame)優化性能。
  • 現代瀏覽器已支援 HTML5 Drag & Drop API,但原生 JS 實現仍具教學價值,且在複雜定製場景下更靈活。

掌握原生拖拽原理,不僅能減少對重型庫的依賴,更能在面試與實戰中遊刃有餘。完整代碼可直接複製運行,歡迎在此基礎上擴展更多交互細節。

copyright © 萬盛學電腦網 all rights reserved