这有点晚了,但我想你可以使用我在遇到类似情况时尝试过的这种方法。这里的优点是没有额外的插件,或者涉及脚本,你也不必在其中引入性能饥渴的轮询。
这种技术使用了 Jquery 的 droppable 必须提供的内置方法和事件。
好的,说得够多了,下面是解决方法:
假设您有两个元素(在我的情况下为图像)并且您不希望它们重叠或检测它们何时重叠,请将这两个元素设为可放置并让它们“接受”对方:
$([div1, div2]).droppable(CONFIG_COLLISSION_PREVENTION_DROPPABLE);
“CONFIG_COLLISSION_PREVENTION_DROPPABLE”如下所示:
var originatingOffset = null;
CONFIG_COLLISSION_PREVENTION_DROPPABLE = {
tolerance: "touch",
activate : function (event, ui) {
// note the initial position/offset when drag starts
// will be usedful in drop handler to check if the move
// occurred and in cae overlap occurred, restore the original positions.
originatingOffset = ui.offset;
},
drop : function (event, ui) {
// If this callback gets invoked, the overlap has occurred.
// Use this method to either generate a custom event etc.
// Here, i used it to nullify the move and resetting the dragged element's
// position back to it's original position/offset
// (which was captured in the 'activate' handler)
$(ui.draggable).animate({
top: originatingOffset.top + "px",
left: originatingOffset.left + "px"
}, 300);
}
}
'activate' 和 'drop' 处理程序是指 "droppable" 插件的 'dropactivate' 和 'drop' 事件
这里的关键是“drop”回调。每当这两个元素中的任何一个重叠并且它们彼此重叠时,都会调用“drop”。这是检测和采取行动的地方,可能是发送自定义事件或调用其他操作(我这里选择在拖动开始时将重叠元素的位置恢复到初始位置,这是在“激活”回调中捕获的)。
就是这样。没有投票,没有插件,只有内置事件。
好吧,可以对其进行其他优化/扩展,这只是我脑海中的第一枪:)
您还可以使用“dropover”和“dropout”事件向用户发出信号并创建视觉反馈,表明两个元素重叠,而它们可能仍在移动中。
var CLASS_INVALID = "invalid";
// .invalid { border: 1px solid red; }
...
$.extend(CONFIG_COLLISSION_PREVENTION_DROPPABLE, {
over : function (event, ui) {
// When an element is over another, it gets detected here;
// while it may still be moved.
// the draggable element becomes 'invalid' and so apply the class here
$(ui.draggable).addClass(CLASS_INVALID);
},
out : function(event, ui) {
// the element has exited the overlapped droppable now
// So element is valid now and so remove the invalid class from it
$(ui.draggable).removeClass(CLASS_INVALID);
}
});
希望这会有所帮助!