我正在尝试拖动包含在较小div中的图像,但是我不希望图像离开div窗口。因此,如果用户向上拖动图像,当图像底部到达父div的底部时,它将停止,左右和顶部相同。
HTML
<div class="window">
<img src="source/to/image" id="draggable-image" />
</div>
CSS
.window {
width: 400px;
height: 200px;
overflow: hidden;
position: relative;
border: 1px solid #000;
}
#draggable-image {
width: 700px;
cursor: move;
}
JS
$(document).ready(function() {
$("#draggable-image").css({top: 0, left: 0});
var maskWidth = $(".window").width();
var maskHeight = $(".window").height();
var imgPos = $("#draggable-image").offset();
var imgWidth = $("#draggable-image").width();
var imgHeight = $("#draggable-image").height();
var x1 = (imgPos.left + maskWidth) - imgWidth;
var y1 = (imgPos.top + maskHeight) - imgHeight;
var x2 = imgPos.left;
var y2 = imgPos.top;
console.log({
'x1' : x1,
'y1' : y1,
'x2' : x2,
'y2' : y2
})
$('#draggable-image').draggable({
containment:[x1,y1,x2,y2],
scroll: false,
drag: function(event, ui) {
console.log({
'Top': $('#draggable-image').offset().top,
'Left': $('#draggable-image').offset().left
});
}
})
});
});
我不知道如何保持正确,并且一旦图像右侧与右侧相交,并且底部与div底部相遇,则停止向下。