jQuery UI Droppable and Sortable - dropping in the correct sort location

前端 未结 2 574
梦谈多话
梦谈多话 2020-12-08 16:42

I\'m working on a project where I\'m dragging elements from a 3rd party jQuery control to a jQuery sortable, using a combination of droppable and sortable.

This work

相关标签:
2条回答
  • 2020-12-08 16:59

    What about doing this? Using both the connectToSortable AND connectWith options works, I think. There might be a more clever way to hide/show the placeholder, but this definitely works.

    $(function () {
        $("#catalog").accordion();
        $("#catalog li").draggable({
            appendTo: "body",
            helper: "clone",
            connectToSortable: "#cart ol"
        });
        $("#cart ol").sortable({
            items: "li:not(.placeholder)",
            connectWith: "li",
            sort: function () {
    
                $(this).removeClass("ui-state-default");
            },
            over: function () {
                //hides the placeholder when the item is over the sortable
                $(".placeholder").hide(); 
    
            },
            out: function () {
                if ($(this).children(":not(.placeholder)").length == 0) {
                    //shows the placeholder again if there are no items in the list
                    $(".placeholder").show();
                }
            }
        });
    });
    

    Work Demo in Fiddle

    0 讨论(0)
  • 2020-12-08 17:07

    use droppable's drop event's callback to compare the current top offset position of the draggable helper with the top offset of every element already present or previously added in the droppable

    drop: function (event, ui) {
    
    if($(this).find(".placeholder").length>0)  //add first element when cart is empty
    {
        $(this).find(".placeholder").remove();
        $("<li></li>").text(ui.draggable.text()).appendTo(this);
    }
    
    else
    {
    
        var i=0; //used as flag to find out if element added or not
    
        $(this).children('li').each(function()
        {
            if($(this).offset().top>=ui.offset.top)  //compare
           {
              $("<li></li>").text(ui.draggable.text()).insertBefore($(this));
              i=1;   
              return false; //break loop
           }
        })
    
        if(i!=1) //if element dropped at the end of cart
        {
            $("<li></li>").text(ui.draggable.text()).appendTo(this);
        }
    
    }
    
    } 
    

    DEMO WITH CODE

    FULL SCREEN DEMO

    0 讨论(0)
提交回复
热议问题