核心原理
mousedown / touchstart:記錄起始座標與元素當前位置
mousemove / touchmove:計算位移,更新元素 left/top
mouseup / touchend:清除移動監聽器
完整實作(支援滑鼠 + 觸控、邊界限制、把手區域)
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>DIV 拖曳範例</title>
<style>
.draggable {
position: absolute;
left: 100px; top: 100px;
width: 300px;
background: #fff;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
user-select: none; /* 防止拖曳時選取文字 */
}
.drag-handle {
height: 40px;
background: #007bff;
color: #fff;
cursor: move; /* 滑鼠游標 */
display: flex; align-items: center; padding: 0 16px;
border-radius: 8px 8px 0 0;
font-weight: bold;
}
.drag-content { padding: 16px; }
</style>
</head>
<body>
<div id="myDraggable" class="draggable">
<div class="drag-handle">拖曳把手(標題列)</div>
<div class="drag-content">
<p>這裡放任意內容:表單、圖表、文字...</p>
<button onclick="alert('內部按鈕可正常點擊')>測試按鈕</button>
</div>
</div>
<script>
(function() {
const el = document.getElementById('myDraggable');
const handle = el.querySelector('.drag-handle');
let startX, startY, initialLeft, initialTop;
let isDragging = false;
// 統一取得 clientX/Y(支援滑鼠與觸控)
function getClientXY(e) {
if (e.touches && e.touches.length) return {x: e.touches[0].clientX, y: e.touches[0].clientY};
return {x: e.clientX, y: e.clientY};
}
function onStart(e) {
// 僅允許從把手區域開始拖曳
if (!handle.contains(e.target)) return;
// 防止觸發瀏覽器預設拖曳行為(如圖片拖曳)
e.preventDefault();
const {x, y} = getClientXY(e);
startX = x; startY = y;
initialLeft = el.offsetLeft;
initialTop = el.offsetTop;
isDragging = true;
// 全域監聽,避免滑鼠移出 handle 區域導致中斷
document.addEventListener('mousemove', onMove);
document.addEventListener('mouseup', onEnd);
document.addEventListener('touchmove', onMove, {passive: false});
document.addEventListener('touchend', onEnd);
handle.style.cursor = 'grabbing';
}
function onMove(e) {
if (!isDragging) return;
e.preventDefault(); // 觸控時防止頁面滾動
const {x, y} = getClientXY(e);
const dx = x - startX;
const dy = y - startY;
// 邊界限制(可選)
const maxX = window.innerWidth - el.offsetWidth;
const maxY = window.innerHeight - el.offsetHeight;
let newLeft = Math.max(0, Math.min(maxX, initialLeft + dx));
let newTop = Math.max(0, Math.min(maxY, initialTop + dy));
el.style.left = newLeft + 'px';
el.style.top = newTop + 'px';
}
function onEnd() {
if (!isDragging) return;
isDragging = false;
document.removeEventListener('mousemove', onMove);
document.removeEventListener('mouseup', onEnd);
document.removeEventListener('touchmove', onMove);
document.removeEventListener('touchend', onEnd);
handle.style.cursor = 'move';
}
// 綁定:僅在把手區域啟動
handle.addEventListener('mousedown', onStart);
handle.addEventListener('touchstart', onStart, {passive: false});
})();
</script>
</body>
</html>
關鍵細節解析
| 細節 | 說明 |
user-select: none | 防止拖曳時文字被選取(CSS) |
e.preventDefault() 在 touchstart | 阻止瀏覽器預設滾動/縮放,確保拖曳優先 |
{passive: false} | 允許在 touchmove 中呼叫 preventDefault |
監聽掛在 document | 滑鼠移出 handle 仍能持續拖曳 |
offsetLeft/Top | 相對 offsetParent 位置,父層若非 static 需注意 |
| 邊界限制 | 防止拖出視窗不可見 |
進階擴充
- 磁吸對齊:移動結束時計算最近網格點
Math.round(left / 20) * 20
- 碰撞偵測:搭配
getBoundingClientRect() 避免重疊其他元素
- 持久化位置:
localStorage.setItem('pos', JSON.stringify({left, top})),下次載入還原
- 多點觸控縮放/旋轉:需引入
InteractJS 或 Hammer.js 函式庫
原始碼重構對照
// 原始碼問題:
var posX, posY; // 全域變數汙染
fdiv = document.getElementById("divBody"); // 隱性全域
document.getElementById("divHead").onmousedown = ... // 直接覆蓋 onmousedown,無法多綁
// 現代寫法:IIFE 封裝、addEventListener、支援觸控、邊界限制、游標回饋