jQuery UI可拖动约束

我想要做的是在一个较小的div中包含一个大图像,用户可以在包含div中拖动(很容易)…类似于http://oneblackbear.com/draggable/index.html但是我想要阻止用户将其拖动到容器边界之外。 使用上面的示例,用户可以将图像完全拖动到包含div之外…我想防止用户将图像拖到父div之外。

我已经尝试过使用jQuery UI draggable,但问题是如果我将图像拖动到右下角并且不再可拖动时使用约束选项,因为子元素大于父约束。 我不确定ui draggable约束是否仅用于较小的对象,而不是父容器。

有没有人有任何想法怎么办? 最好用jQuery Draggable?

var productHeadOffset = jQuery('#productHead').offset(); var productHeadHeight = jQuery('#productHead').height(); var productHeadWidth = jQuery('#productHead').width(); var productHeadImageHeight = jQuery('.productHeadImage').height(); var right = productHeadOffset.left; var bottom = productHeadOffset.top; var left = (img.width > productHeadWidth) ? (productHeadWidth + productHeadOffset.left) - img.width : 0; var top = (img.height > productHeadImageHeight) ? (productHeadHeight + productHeadOffset.left) - img.height : 0; jQuery('.productHeadImage').draggable({ containment: [left, top, right, bottom] }); 

这个解决方案对我有用,虽然滚动页面时Chrome仍然存在问题:

 var cropBoundsOffset = $("cropBounds").offset(); var cropBoundsHeight = $("cropBounds").height(); var cropBoundsWidth = $("cropBounds").width(); var imageHeight = $("cropImage").height(); var imageWidth = $("cropImage").width(); var right = cropBoundsOffset.left; var bottom = cropBoundsOffset.top; var left = (imageWidth > cropBoundsWidth) ? (cropBoundsWidth + cropBoundsOffset.left) - imageWidth : 0; var top = (imageHeight > cropBoundsHeight) ? (cropBoundsHeight + cropBoundsOffset.top) - imageHeight : 0; var border_left = parseInt($("cropBounds").css("border-left-width")); var border_top = parseInt($("cropBounds").css("border-top-width")); $("cropImage").draggable("option", "containment", [ left + border_left, top + border_top, right, bottom ]);