利用三個滑鼠事件:
mousedown:記錄滑鼠相對元素左上角的偏移量mousemove:依滑鼠位置計算元素新位置並更新mouseup:結束拖曳.drag {
position: absolute;
background: #0000CC;
top: 100px; left: 200px;
padding: 0;
cursor: move; /* 提示可拖曳 */
}
$(document).ready(function() {
var move = false; // 拖曳狀態旗標
var _x, _y; // 滑鼠相對元素左上角偏移
$(".drag").mousedown(function(e) {
move = true;
_x = e.pageX - parseInt($(this).css("left"));
_y = e.pageY - parseInt($(this).css("top"));
$(this).css("opacity", 0.8); // 視覺回饋
});
$(document).mousemove(function(e) {
if (!move) return;
var x = e.pageX - _x;
var y = e.pageY - _y;
$(".drag").css({ "top": y, "left": x });
}).mouseup(function() {
move = false;
$(".drag").css("opacity", 1);
});
});
e.pageX/Y:滑鼠相對文件左上角座標(含捲軸)parseInt(css("left")):元素目前 left 數值_x = pageX - left:滑鼠點擊點相對元素左上角的固定偏移新 left = pageX - _x,保持相對位置不變Math.max(0, Math.min(maxX, x))touchstart/move/end 事件$("#draggable").draggable(); 一行搞定