mousedown。document 上綁定 mousemove/mouseup,防止鼠標移出元素導致事件丟失。left/top,並做邊界限制。e.preventDefault(); // Chrome/Firefox/IE9+
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); // 兼容舊 IE
e.preventDefault(); // 在 mousemove 中調用,阻止瀏覽器顯示「禁止」圖標
// 錯誤寫法:直接判斷範圍會導致邊緣卡頓
if (x >= limit._left && x <= limit._right) { $target.css({left: x}); }
// 正確寫法:先計算再鉗制
if (x < limit._left) x = limit._left;
if (x > limit._right) x = limit._right;
// 或一行式
$target.css({
left: Math.max(Math.min(x, limit._right), limit._left) + 'px',
top: Math.max(Math.min(y, limit._bottom), limit._top) + 'px'
});
$.fn.extend({
drag: function(options) {
var dragStart, dragMove, dragEnd, $boundaryElem, limitObj;
function _initOptions() {
var noop = function(){}, defaultOptions = { boundaryElem: 'body' };
options = $.extend(defaultOptions, options || {});
$boundaryElem = $(options.boundaryElem);
dragStart = options.dragStart || noop;
dragMove = options.dragMove || noop;
dragEnd = options.dragEnd || noop;
}
function _drag(e) {
var clientX = e.clientX, clientY = e.clientY;
var $target = $(this), self = this;
var offsetLeft = this.offsetLeft, offsetTop = this.offsetTop;
limitObj = {
_left: 0,
_top: 0,
_right: ($boundaryElem.innerWidth() || $(window).width()) - $target.outerWidth(),
_bottom: ($boundaryElem.innerHeight() || $(window).height()) - $target.outerHeight()
};
dragStart.apply(self, arguments);
$(document).bind('mousemove', moveHandle).bind('mouseup', upHandle);
function moveHandle(e) {
var x = e.clientX - clientX + offsetLeft;
var y = e.clientY - clientY + offsetTop;
$target.css({
left: Math.max(Math.min(x, limitObj._right), limitObj._left) + 'px',
top: Math.max(Math.min(y, limitObj._bottom), limitObj._top) + 'px'
});
dragMove.apply(self, arguments);
e.preventDefault(); // 阻止圖片默認拖拽
}
function upHandle(e) {
$(document).unbind('mousemove', moveHandle).unbind('mouseup', upHandle);
dragEnd.apply(self, arguments);
}
}
_initOptions();
return this.css({position: 'absolute'}).each(function() {
$(this).bind('mousedown', function(e) {
_drag.apply(this, [e]);
e.preventDefault();
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
});
});
}
});
$('.drag-elem').drag({
boundaryElem: '#boundary',
dragStart: function() { console.log('開始拖拽'); },
dragMove: function() { /* 實時回調 */ },
dragEnd: function() { console.log('結束拖拽'); }
});
同理可用 addEventListener 實現,邏輯完全一致,適合無 jQuery 環境。
拖拽核心 = 事件委託到 document + 偏移量計算 + 邊界鉗制。掌握此模式,可擴展至調整大小、排序、畫布繪圖等交互。