拖拽是前端基本功,而「拖動移動 + 邊角縮放」是它的進階版本。這個示例在本地支援 IE6,做法是把移動與縮放拆成兩套邏輯,共用同一套座標計算。
作者當時遇到一個問題:滑鼠點擊時光標會變成選取文字的光標。這個問題的解法是在拖動過程中阻止預設行為——IE 用 document.onselectstart = function(){ return false },標準瀏覽器則在 mousedown 時呼叫 e.preventDefault(),同時給可拖動區域加上 user-select: none。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>簡單拖拽擴展</title>
<style type="text/css">
* { margin: 0; padding: 0; }
#outwarp {
margin: 20px auto;
width: 600px;
height: 600px;
background: #fff;
border: 1px solid #333;
position: relative;
}
.controlBox {
width: 200px;
height: 200px;
position: absolute;
left: 25px;
top: 50px;
background: #ccc;
font-size: 12px;
color: #fff;
border: 1px solid #333;
}
.controlBar { cursor: move; }
.controlBar h2 {
font-size: 12px;
text-align: center;
line-height: 25px;
background: blue;
}
.innerCon { text-align: left; line-height: 20px; }
.innerCon p { padding: 10px; color: #000; }
/* 四個縮放把手 */
.resize {
position: absolute;
height: 10px;
width: 10px;
color: white;
z-index: 10;
background: red;
}
.lt { left: 0; top: 0; cursor: nw-resize; }
.tr { right: 0; top: 0; cursor: ne-resize; }
.rb { right: 0; bottom: 0; cursor: nw-resize; }
.bl { left: 0; bottom: 0; cursor: ne-resize; }
</style>
</head>
<body>
<div id="outwarp">
<div class="controlBox">
<div class="controlBar">
<h2>按此處拖動</h2>
</div>
<span class="resize lt"</span>
<span class="resize tr"</span>
<span class="resize rb"</span>
<span class="resize bl"</span>
<div class="innerCon">
<p>中間內容中間內容中間內容……</p>
</div>
</div>
</div>
<script type="text/javascript">
// 通用事件綁定,抹平 IE 與標準瀏覽器差異
function addEvent(el, type, fn) {
if (el.addEventListener) {
el.addEventListener(type, fn, false);
} else {
el.attachEvent('on' + type, fn);
}
}
function getStyle(el, prop) {
return el.currentStyle ? el.currentStyle[prop]
: getComputedStyle(el, null)[prop];
}
var box = document.querySelector('.controlBox');
var bar = document.querySelector('.controlBar');
var wrap = document.getElementById('outwarp');
// 阻止拖動過程中選中文本
document.onselectstart = function () { return false; };
// 拖動移動
addEvent(bar, 'mousedown', function (e) {
e = e || window.event;
e.preventDefault && e.preventDefault();
var startX = e.clientX;
var startY = e.clientY;
var left = box.offsetLeft;
var top = box.offsetTop;
document.onmousemove = function (e2) {
e2 = e2 || window.event;
var nx = left + e2.clientX - startX;
var ny = top + e2.clientY - startY;
// 邊界約束,避免拖出容器
var maxX = wrap.clientWidth - box.offsetWidth;
var maxY = wrap.clientHeight - box.offsetHeight;
if (nx < 0) nx = 0;
if (ny < 0) ny = 0;
if (nx > maxX) nx = maxX;
if (ny > maxY) ny = maxY;
box.style.left = nx + 'px';
box.style.top = ny + 'px';
};
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
};
return false;
});
// 縮放:四個把手共用
var handles = document.querySelectorAll('.resize');
for (var i = 0; i < handles.length; i++) {
(function (handle) {
addEvent(handle, 'mousedown', function (e) {
e = e || window.event;
e.preventDefault && e.preventDefault();
var dir = handle.className.replace('resize', '').trim();
var startX = e.clientX;
var startY = e.clientY;
var w = box.offsetWidth;
var h = box.offsetHeight;
var left = box.offsetLeft;
var top = box.offsetTop;
document.onmousemove = function (e2) {
e2 = e2 || window.event;
var dx = e2.clientX - startX;
var dy = e2.clientY - startY;
var nw = w, nh = h, nl = left, nt = top;
if (dir.indexOf('r') > -1) { // 右側把手:改寬
nw = w + dx;
}
if (dir.indexOf('l') > -1) { // 左側把手:改寬並同時調整 left
nw = w - dx;
nl = left + dx;
}
if (dir.indexOf('b') > -1) { // 下側把手:改高
nh = h + dy;
}
if (dir.indexOf('t') > -1) { // 上側把手:改高並同時調整 top
nh = h - dy;
nt = top + dy;
}
// 最小尺寸限制
if (nw < 80) {
nw = 80;
if (dir.indexOf('l') > -1) nl = left + (w - 80);
}
if (nh < 40) {
nh = 40;
if (dir.indexOf('t') > -1) nt = top + (h - 40);
}
// 不要超出容器
if (nl < 0) { nw += nl; nl = 0; }
if (nt < 0) { nh += nt; nt = 0; }
if (nl + nw > wrap.clientWidth) nw = wrap.clientWidth - nl;
if (nt + nh > wrap.clientHeight) nh = wrap.clientHeight - nt;
box.style.width = nw + 'px';
box.style.height = nh + 'px';
box.style.left = nl + 'px';
box.style.top = nt + 'px';
};
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
};
return false;
});
})(handles[i]);
}
</script>
</body>
</html>
移動的關鍵是「差值」。記錄 mousedown 時的滑鼠座標與元素位置,mousemove 時用當前座標減去起始座標得到位移量,再疊加到起始位置上。直接用 e.clientX 當作元素的 left 是最常見的錯誤,會導致元素左上角瞬移到滑鼠位置。
縮放的關鍵是「方向判斷」。把 class 名稱裡的 l/r/t/b 拆出來判斷:右側把手只改寬度,左側把手改寬度的同時還要往左補償 left,否則元素會看起來是「右邊在動」而不是「左邊在動」。
事件要綁在 document 上,不是元素上。mousemove 與 mouseup 掛在 document,是因為滑鼠可能快速移出元素範圍,掛在元素上會「丟失」拖動。每次 mouseup 時記得把 document 上的臨時監聽清掉,避免記憶體洩漏與多個閉包同時生效。
邊界約束分兩層。移動時限制 left/top 不超過容器可移動範圍;縮放時除了最小尺寸,還要處理「往左上縮放時不能超出容器左側與頂部」這種情況,需要把超出的量從寬高裡扣掉。
現代寫法的差異。ES6 之後可以直接用 let 免去 IIFE 閉包傳參;PointerEvent(pointerdown/pointermove/pointerup)統一了滑鼠、觸控與手寫筆,配合 setPointerCapture 就不需要把監聽掛在 document 上;CSS 的 resize 屬性與 touch-action: none 也能省下不少手寫邏輯。但底層的座標差值計算思路是不變的。