拖曳(drag & drop)是許多互動元件的基礎。以下範例用 jQuery 做一個可以隨滑鼠移動的方塊,邏輯簡單,適合入門參考。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JavaScript 拖曳</title>
<style>
.test {
text-align: center;
width: 300px;
height: 30px;
line-height: 30px;
background: #f60;
position: absolute;
}
.test:hover { cursor: move; }
</style>
</head>
<body>
<script src="jquery-1.6.2.min.js"></script>
<div class="test">拖曳測試</div>
<br/><br/>
<h1>如果無效請重新整理頁面</h1>
<script>
$(function () {
var isMove = false;
$(".test")
.mousedown(function () { isMove = true; })
.mouseup(function () { isMove = false; });
$(document).mousemove(function (e) {
if (!isMove) { return; }
// 讓游標位于方塊中心
var X = e.clientX - parseInt($(".test").width() / 2);
var Y = e.clientY - parseInt($(".test").height() / 2);
$(".test").css({ "left": X, "top": Y, "cursor": "move" });
});
});
</script>
</body>
</html>
用一個 isMove 旗標記錄「目前是否處於按下狀態」。在元素上按下滑鼠時設為 true,放開時設回 false;全域的 mousemove 則只在旗標為 true 時才更新位置。之所以把 mouseup 綁在元素上卻在文件上監聽移動,是因為滑鼠可能移出元素範圍,若不在 document 上監聽就會「拖到一半卡住」。
(function () {
var box = document.querySelector('.test');
var offsetX = 0, offsetY = 0, dragging = false;
box.addEventListener('mousedown', function (e) {
dragging = true;
// 記錄游標與元素左上角的偏移,避免拖曳時跳位
offsetX = e.clientX - box.offsetLeft;
offsetY = e.clientY - box.offsetTop;
e.preventDefault(); // 避免選取到文字
});
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;
});
})();
pointerdown/pointermove/pointerup 同時支援滑鼠、觸控與手寫筆,並可用 setPointerCapture() 確保拖曳中不中斷。Math.max(0, Math.min(x, 視窗寬度 - 元素寬度)) 夾住座標。draggable="true" 搭配 dragstart、dragover、drop 事件,適合清單排序或資料搬移;但無法自訂「跟著游標跑」的視覺效果。touch-action: none,否則瀏覽器的捲動手勢會搶走事件。