我最近使用下面的代碼來創建一個可拖動的jQuery擴展。您可以傳遞拖動動作的目標。
(function ($) {
var element;
var target;
var settings = {
onDrop: function (x, y) { }
};
var methods = {
init: function (options) {
if (options) {
$.extend(settings, options);
}
return this.each(function() {
// Code here for each element found by the selector
element = $(this);
if (options.target) {
target = $(options.target);
}
else {
target = element;
}
// Move the element by the amount of change in the mouse position
element.parent().mousedown(function (event) {
element.data('mouseMove', true);
element.data('mouseX', event.clientX);
element.data('mouseY', event.clientY);
});
element.parents(':last').mouseup(function() {
element.data('mouseMove', false);
});
element.mouseout(methods.move);
element.mousemove(methods.move);
});
},
move: function (event) {
if (element.data('mouseMove')) {
var changeX = event.clientX - element.data('mouseX');
var changeY = event.clientY - element.data('mouseY');
var newX = parseInt(target.css('margin-left')) + changeX;
var newY = parseInt(target.css('margin-top')) + changeY;
target.css({ 'margin-left': newX, 'margin-top': newY });
settings.onDrop(newX, newY);
element.data('mouseX', event.clientX);
element.data('mouseY', event.clientY);
}
}
};
$.fn.draggable = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.draggable');
return null;
}
};
})(jQuery);
然後調用它像這樣:
$('#overlay').draggable({ target: "#imagebehide", onDrop: function (x, y) {
$('#leftpos').val(x);
$('#toppos').val(y);
} });