JQuery UI: Cancel Sortable upon Droppable Drop

廉价感情. 提交于 2019-12-05 01:40:37

OK, so I have worked out a solution which does the job.

the cancel code does work if you have it in the "stop" event of the sortable function. However, it will only apply once the "revert" has completed. The problem is that I was trying to copy/revert the element from the droppable "drop" event and this was too early.

The solution is to wait for the "stop" event to complete, and to achieve this I had to create a "awaiting copy" flag, to be checked in the "stop" event.

Here is an example

It still doesn't feel right (UX-wise) but it works correct, and you could always set revert to false on the sortable function to get a slightly better feel.

The code from the example is as follows...

var itemCount = 3;
var awaitingCopy = false;

$(init);

function init() {
    $("#Items").sortable({
        revert: true,
        placeholder: "ItemPlaceHolder",
        opacity: 0.6,
        start: StartDrag,
        stop: StopDrag
    });

    $("#CopyItem").droppable({
        hoverClass: "CopyItemActive",
        drop: function(event, ui) {
            awaitingCopy = true;
        }
    });

    $("#NewItem").click(function(e) {
        e.preventDefault();
        itemCount++;
        var element = $("<div class='Item'>Item " + itemCount + "</div>");
        $("#Items").append(element);
        element.hide().slideDown(500);
    });
}

function CopyItem(element) {
    awaitingCopy = false;
    var clone = element.clone();
    $("#Items").append(clone);
    clone.hide().slideDown(500);
}

function StartDrag() {
    $("#NewItem").hide();
    $("#CopyItem").show();
}

function StopDrag(event, ui) {
    if (awaitingCopy) {
        $(this).sortable('cancel');
        CopyItem($(ui.item));
    }
    $("#NewItem").show();
    $("#CopyItem").hide();
}

Anyway, hopefully this will help others who want the same kind of effect... no stealing my design though ;)

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