Drag and drop with 2 drop target

社会主义新天地 提交于 2019-12-04 19:23:32

You can accomplish this by using a combination of draggable/droppable options. Given HTML like this:

<div id="blue" class="valid">
    <div id="red-one" class="red"></div>
    <div id="red-two" class="red"></div>
</div>

<div id="green-container">
    <div id="green-one" class="green">
    </div>
    <div id="green-two" class="green">
    </div>
</div>

(omitting CSS, I did add some rules, see in the fiddle below).

You can write JavaScript like this:

function isInside(one, other) {
    return one.offset().left >= other.offset().left &&
        one.offset().top >= other.offset().top &&
        one.offset().top + one.height() <= other.offset().top + other.height() &&
        one.offset().left + one.width() <= other.offset().left + other.width();
}

$("#blue").draggable({
    drag: function(event, ui) {
        var $this = $(this);
        var $reds = $this.children(".red");
        var $greens = $("#green-container").children(".green");
        var firstRed = $reds.first();
        var firstGreen = $greens.first();
        var secondRed = $reds.last();
        var secondGreen = $greens.last();

        if (isInside(firstRed, firstGreen) && isInside(secondRed, secondGreen)) {
            $this.addClass('valid');
        }
        else {
            $this.removeClass('valid');
        }       
    },
    revert: 'invalid'
});


$("#green-container").droppable({ accept: ".valid" });

Check it out here: http://jsfiddle.net/andrewwhitaker/g6FKz/

Notes:

  • For some reason I had to apply the 'valid' class initially to the 'blue' div, or else the target droppable would not accept the dragged element, even if it was valid (would appreciate some input on this). Not sure what's up with that, might be a bug in jQueryUI. Not a huge deal though.
  • The target droppable isn't exactly the two green elements, it's a white div that contains those elements. This should be clear from the example.
  • Every time you move the draggable div, the "drag" event is called, which determines if the red boxes are inside the green ones and assigns a valid class to the draggable div. The droppable object only accepts valid draggables.

Hope that helps!

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