不依賴 jQuery UI,僅用核心 jQuery 實作基本拖曳:滑鼠按下記錄起始座標、移動時計算位移更新 left/top、放開釋放捕獲。
dragging = true,記錄 iX = e.clientX - offsetLeft、iY = e.clientY - offsetTop,呼叫 setCapture()(IE)防止滑鼠移出元素失去事件。dragging 計算 oX = e.clientX - iX、oY = e.clientY - iY,套用 css({left: oX, top: oY})。dragging = false,releaseCapture(),cancelBubble = true 阻止冒泡。<style>
#drag { width:400px; height:300px; background:url(...); cursor:move; position:absolute; top:100px; left:100px; border:1px solid #ccc; }
h2 { background:rgba(16,90,31,0.7); color:#fff; height:40px; line-height:40px; margin:0; }
</style>
<script src="jquery.min.js"></script>
<script>
$(function() {
var dragging = false, iX, iY;
$("#drag").mousedown(function(e) {
dragging = true;
iX = e.clientX - this.offsetLeft;
iY = e.clientY - this.offsetTop;
this.setCapture && this.setCapture();
return false;
});
$(document).mousemove(function(e) {
if (!dragging) return;
var oX = e.clientX - iX;
var oY = e.clientY - iY;
$("#drag").css({ left: oX + "px", top: oY + "px" });
return false;
});
$(document).mouseup(function() {
dragging = false;
$("#drag")[0].releaseCapture && $("#drag")[0].releaseCapture();
});
});
</script>
<div id="drag"><h2>來拖動我啊</h2></div>
Math.min/max 限制在視窗內)。touchstart/move/end)適配行動裝置。SortableJS、interact.js 或 jQuery UI Draggable。