一方面,您已经通过 jQuery 插件和您自己的代码使图像可拖动。您的代码正在更改 的background-position
,div
而 jQuery 插件正在更改div
的实际位置。这势必会引起一些问题。
此外, Draggable 的containment
参数似乎是为小于其父容器的可拖动项目设计的,而不是像您尝试做的那样更大的项目。
无论如何,这是工作代码:
$(document).ready(function() {
$(".draggable").draggable().bind('dragstop', function(e, ui) {
if (ui.position.top > 0) {
$(this).css('top', 0);
}
if (ui.position.left > 0) {
$(this).css('left', 0);
}
var bottom = -($(this).height() - $(this).parent().height()),
right = -($(this).width() - $(this).parent().width());
if (ui.position.top < bottom) {
$(this).css('top', bottom);
}
if (ui.position.left < right) {
$(this).css('left', right);
}
});
});
如果您不需要边缘捕捉,您可以摆脱该.bind()
功能,只需调用.draggable()
.
$(document).ready(function() {
$(".draggable").draggable();
});