Restrict jQuery draggable items from overlapping/colliding with sibling elements

前端 未结 2 571
谎友^
谎友^ 2020-11-30 09:04

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 ot

2条回答
  •  日久生厌
    2020-11-30 10:05

    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/

提交回复
热议问题