Restrict jQuery draggable items from overlapping/colliding with sibling elements

时间秒杀一切 提交于 2019-11-27 04:40:51

Edit: New Solution

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.)

Here is the code:

$("#dragMe").draggable({
    obstacle: "#butNotHere",
    preventCollision: true,
    containment: "#moveInHere"
});

Old Solution

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"
});​

This took me quite a bit of fiddling. Basically I created a droppable on the element you want to avoid, then set a boolean when the drag is over it. I then use that in an undocumented revert function override to cancel the drop. It only works if #dragMe is fully over #butNotHere:

$(document).ready(function(){
    var shouldCancel = false;
    $('#dragMe').draggable({
        containment: '#moveInHere',
        revert: function(){
            if (shouldCancel) {
                shouldCancel = false;
                return true;
            } else {
                return false;
            }
        }
    });
    $('#butNotHere').droppable({
        over: function(){
            shouldCancel = true;
        },
        out: function(){
            shouldCancel = false;
        }
    });
});

Check out the working demo and feel free to play with it: http://jsfiddle.net/H59Nb/31/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!