jQuery UI Draggable Constraint
what I am trying to do is have an large image contained within a smaller div that the user can drag around within the containing div (easy enough)... similar to http://oneblackbear.com/draggable/index.html but I want to prevent users from dragging it any further then the container boundary. With the above example the user can drag the image completely outside of the containing div... I want to prevent the user from ever dragging the image outside of the parent div at all.
I have tried using jQuery UI draggable but the prob开发者_如何学JAVAlem is if I use the constraint option as soon as you drag the image it locks to the bottom right and is no longer draggable because the child element is larger then the parent constraint. I am not sure if the ui draggable constraint is only intended for smaller objects then the parent container.
Does anyone have any ideas how do do with? preferably with 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] });
This is the solution that worked for me, although I'm still having issues in Chrome when the page is scrolled:
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
]);
精彩评论