我们说我有父容器(点缀),溢出:隐藏。在里面我有一个超过容器边界的div(灰色,红色是容器外面的隐藏部分)。这个div是一个Jquery UI可放置对象。
问题:
容器外部的div部分仍然可以放置。如何停止此行为并仅允许容器内的部件可以放置?
谢谢!
答案 0 :(得分:1)
请参阅我对上下文的评论,但这是jsFiddle处可能解决方案的第一步。我假设父(虚线)容器不是可放置的。
$(".drag").draggable();
$(".child").droppable({
drop: function (event, ui) {
/*
* Check if draggable is inside the parent. This is a bit brute force, if
* the parent itself is also a droppable it can also be checked by
* listening for the 'over' event and setting a flag.
*/
var pPos = $(".parent").offset(); // the parent container's position
var dPos = ui.offset; // the current draggable's position
// Can also add right/top/bottom contraints if required...?
var withinParent = dPos.left > pPos.left;
if (!withinParent) {
// Move the draggable to its original position (or some safe spot)
ui.draggable.animate(ui.draggable.data().draggable.originalPosition, "slow");
}
}
});
如果你正在为你的draggable使用帮助器,那么这个逻辑应该进入可拖动的revert
回调。请参阅新的jsFiddle。
我做了一些假设可能是错误的,所以一定要阅读javascript评论!祝你好运=)
$(".drag").draggable({
helper: "clone",
revert: function () {
/*
* Check if draggable is inside the parent. This is a bit brute force, if
* the parent itself is also a droppable it can also be checked by
* listening for the 'over' event and setting a flag.
*/
// The parent container's position
var pPos = $(".parent").offset();
// The current draggable helper's position
var dDraggable = this.data().draggable;
var helper = dDraggable.helper;
var dPos = helper.offset();
/*
* Can also add top and right/bottom contraints
* if we only want to allow dragging onto droppable!
* Will have to calculate right = left + width,
* bottom = top + height. Also take into account possible
* borders/padding/margin with jQuery outerWidth!
*/
var withinParent = dPos.left > pPos.left;
if (!withinParent) {
return true;
}
else {
// Move the draggable to the helper's position
// NOTE: We're using offset here, so you may want to test this under various condition, e.g. relative/absolute parents!
this.css(helper.offset());
return false;
}
}
});
$(".child").droppable();