在无法使用 jQuery 找到解决方案后,我实现了自己的拖动 - 对我很有用。它还允许我删除 jQuery UI,这很棒。请注意,draggable 和 handle 是 jquery 元素,而 limits 是一个对象。这是代码 -
function initializeDrag(draggable, handle, limits) {
var initialMousePosition, initialDraggablePosition;
handle.on('mousedown', function (e) {
initialMousePosition = {
x: e.pageX,
y: e.pageY
};
initialDraggablePosition = {
top: parseInt(draggable.css('top'), 10),
left: parseInt(draggable.css('left'), 10)
}
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
});
function onMouseMove(e) {
var verticalDelta = e.pageY - initialMousePosition.y;
var horizontalDelta = e.pageX - initialMousePosition.x;
var topRes = initialDraggablePosition.top + verticalDelta;
var leftRes = initialDraggablePosition.left + horizontalDelta;
topRes = Math.max(topRes, limits.top);
topRes = Math.min(topRes, limits.bottom);
leftRes = Math.max(leftRes, limits.left);
leftRes = Math.min(leftRes, limits.right);
draggable.css({
top: topRes + 'px',
left: leftRes + 'px'
});
}
function onMouseUp() {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
}
}