在前端開發中,拖拽交互是常見需求。雖然 jQuery UI 的 draggable 成熟穩定,但深入理解原生 JS 實現原理,有助於靈活應對定製化場景。本文將從零開始,逐步講解如何用純 JavaScript 實現一個簡單且可複用的拖拽插件。
首先準備一個可拖拽的方塊元素,並設置基本樣式:
<!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>
為了支援多個元素同時拖拽,將邏輯封裝為可複用的類:
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)優化性能。掌握原生拖拽原理,不僅能減少對重型庫的依賴,更能在面試與實戰中遊刃有餘。完整代碼可直接複製運行,歡迎在此基礎上擴展更多交互細節。