How to swap 2 items using Draggable and Droppable?

♀尐吖头ヾ 提交于 2019-12-04 14:59:46

My solution might not be the most elegant (maybe someone can provide something more intuitive?), but it seems it works ;)

Fiddle: http://jsfiddle.net/W9Z46/14/

(function ($) {
    var lastPlace;

    $("#choises li img").draggable({
        revert: true,
        zIndex: 10,
        snap: "#answers li",
        snapMode: "inner",
        snapTolerance: 40,
        start: function (event, ui) {
            lastPlace = $(this).parent();
        }
    });

    $("#answers li").droppable({
        drop: function (event, ui) {
            var dropped = ui.draggable;
            var droppedOn = this;

            if ($(droppedOn).children().length > 0) {
                $(droppedOn).children().detach().prependTo($(lastPlace));
            }

            $(dropped).detach().css({
                top: 0,
                left: 0
            }).prependTo($(droppedOn));
        }
    });
})(jQuery);

As you can see I'm just keeping the place you started draggin from in a variable lastPlace and later when you drop and check something is there, you place it in the place you started dragging before.

You should probably try with sortable instead of droppable in the receiving list. That should give you the functionality you are looking for.

I also to encountered same problem.But my code is a little different.

    $(document).ready(function(){
    var x=[60,270,480];
    var y=[170,170,170];

    $(".draggable").draggable({
        revert:"invalid",
        start:function(){

        }
    });

    $(".droppable").droppable({
        accept:".draggable",
        hoverClass:"active",
        drop:function(ev,ui){
            if($(this).attr("name")!=null){
               var d=$(this).attr("name");
               var dgid=$(ui.draggable).attr("data-id")-1;
               $("#"+d).animate({left:x[dgid],top:y[dgid]});
               $("#drop"+$(ui.draggable).attr("data-id")).attr("name",$(this).attr("name"));
               $("#"+d).attr("data-id",$(ui.draggable).attr("data-id"));
            }
            var dpid=$(this).attr("data-id")-1;
            $(this).attr("name",$(ui.draggable).attr("id"));
            $(ui.draggable).attr("data-id",$(this).attr("data-id"));
            $(ui.draggable).animate({left:x[dpid],top:y[dpid]},300);
        }
    });
});

Check out Fiddle

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