限制jQuery可拖动项与同级元素重叠/碰撞 [英] Restrict jQuery draggable items from overlapping/colliding with sibling elements
问题描述
我需要使用jQuery UI来限制可拖动对象的包含区域,并附加一些限制.我需要防止可拖动元素与同一容器中的其他元素重叠.我需要允许在"moveInHere"区域中移动,但不允许在"butNotHere"区域中移动.有可能吗?
I need to use jQuery UI to restrict the containment area for draggable object with some additional restriction. I need prevent the draggable element from overlapping with other elements within the same container. I need to allow movement in "moveInHere" area but not "butNotHere" area. Is it possible?
<div id="moveInHere">
<div id="dragMe"> </div>
<div id="butNotHere"> </div>
</div>
<script type="text/javascript">
$("#dragMe").draggable({
containment: "#moveInHere"
});
</script>
推荐答案
新解决方案
我为此找到了一个名为 JQuery UI可拖动碰撞的插件.使用此功能,实现所需的功能就变得微不足道了.请参见以下jsFiddle示例: http://jsfiddle.net/q3x8w03y/1/(此版本使用JQuery UI Draggable Collision的1.0.2,以及JQuery 1.7.2和JQueryUI 1.1.18.)
I found a plugin for this called JQuery UI Draggable Collision. Using this, implementing your desired functionality becomes trivial. See the following jsFiddle example: http://jsfiddle.net/q3x8w03y/1/ (This uses version 1.0.2 of JQuery UI Draggable Collision, along with JQuery 1.7.2 and JQueryUI 1.1.18.)
这是代码:
$("#dragMe").draggable({
obstacle: "#butNotHere",
preventCollision: true,
containment: "#moveInHere"
});
旧解决方案
以下应该起作用.不过,它有一个小故障. div碰撞后,您必须重新拖动要拖动的div,这可能会有些烦人.也许其他人会知道如何解决此问题.您可以在此处看到我的jsFiddle示例:
The following should work. It has a glitch, though. Once the divs collide, you have to "regrab" the div you are dragging, which can be a little annoying. Perhaps someone else will know how to fix this this. You can see my jsFiddle example here: http://jsfiddle.net/MrAdE/8/
var prevOffset, curOffset;
$("#dragMe").draggable({
drag: function(e,ui) {
prevOffset= curOffset;
curOffset= $.extend({},ui.offset);
return true;
}
});
$("#butNotHere").droppable({
greedy: true,
over: function(e,ui) {
ui.helper.offset(curOffset= prevOffset).trigger("mouseup");
},
tolerance: "touch"
});
这篇关于限制jQuery可拖动项与同级元素重叠/碰撞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!