拖曳互動的三要素是:在 mousedown 記下起點、在 mousemove 持續更新位置、在 mouseup 解除監聽。原理不難,但細節決定手感。
<html>
<head>
<script type="text/javascript">
var x;
var y;
function $(id)
{
return document.getElementById(id);
}
function mousedown()
{
// 記下滑鼠位置與元素目前位置的差值,避免按下瞬間元素「跳」一下
x = event.clientX - $("px").style.pixelLeft;
y = event.clientY - $("px").style.pixelTop;
$("px").style.border = "2px solid red";
$("px").onmousemove = mousemove;
}
function mouseup()
{
$("px").onmousemove = "";
$("px").style.border = "";
}
function mousemove()
{
$("px").style.pixelLeft = event.clientX - x;
$("px").style.pixelTop = event.clientY - y;
}
</script>
</head>
<body>
<div id="px" style="position:absolute; left:100px; height:100px; width:100px; background-color:#FF0;"
onmousedown="mousedown()" onmouseup="mouseup()">
</div>
</body>
</html>
如果直接在 mousemove 裡寫 left = event.clientX,會發現方塊的左上角瞬間吸附到滑鼠位置,畫面跳一下。原因是使用者可能是在方塊的中央按下,而非左上角。
所以在 mousedown 時先記下「滑鼠位置 − 元素位置」的偏移量,之後每次移動都用「滑鼠位置 − 偏移量」計算新座標,方塊才會乖乖地跟著滑鼠走,維持按下時的相對位置。這是拖曳功能最關鍵的一步。
· pixelLeft/pixelTop 是 IE 專屬語法。在 Firefox、Chrome 上完全無效,元素不會動。標準寫法應該用 parseInt(el.style.left, 10)。
· 全域 event 物件不是標準。應該由事件處理函數的參數接收,或使用 window.event || e 兼容。
var dragging = false, offsetX = 0, offsetY = 0;
var box = document.getElementById('px');
box.addEventListener('mousedown', function(e){
dragging = true;
offsetX = e.clientX - box.offsetLeft;
offsetY = e.clientY - box.offsetTop;
box.style.border = '2px solid red';
e.preventDefault(); // 避免選取到文字
e.stopPropagation();
});
document.addEventListener('mousemove', function(e){
if (!dragging) return;
box.style.left = (e.clientX - offsetX) + 'px';
box.style.top = (e.clientY - offsetY) + 'px';
});
document.addEventListener('mouseup', function(){
dragging = false;
box.style.border = '';
});
這裡有兩個重要調整:把 mousemove/mouseup 掛在 document 而不是元素上,這樣滑鼠移出方塊範圍時仍然能繼續拖;並在 mousedown 時呼叫 preventDefault(),避免拖曳過程中誤選到文字。
若要進一步支援觸控裝置,可以把三個事件換成 touchstart/touchmove/touchend,並從 e.touches[0].clientX 取座標;或直接改用 Pointer Events(pointerdown/pointermove/pointerup),一套程式碼同時處理滑鼠、觸控與觸筆。HTML5 的原生拖曳 API(draggable="true" 加 dragstart/dragover/drop)則更適合「把 A 拖到 B 上」這類資料搬移情境,而自由移動位置仍是以座標運算為主。