jQuery UI Droppable和Sortable - 放入正确的排序位置

Aar*_*onS 16 jquery jquery-ui jquery-ui-sortable jquery-ui-droppable

我正在开发一个项目,我将元素从第三方jQuery控件拖动到jQuery可排序,使用droppable和sortable的组合.

这种方法非常好,除了添加的项目始终添加到可排序列表的底部,然后您必须将其作为单独的步骤移动到正确的位置.

是否可以将项目添加到您将其放入列表中的位置?

您可以在此处的jQuery购物卡可放置演示中看到此行为.这是一个相同代码的jsfiddle.当您将产品中的商品添加到底部的购物车时,它总是会添加到底部,即使您将其放在顶部附近也是如此.

这是jQuery代码:

     $(function () {
     $("#catalog").accordion();
     $("#catalog li").draggable({
         appendTo: "body",
         helper: "clone"
     });
     $("#cart ol").droppable({
         activeClass: "ui-state-default",
         hoverClass: "ui-state-hover",
         accept: ":not(.ui-sortable-helper)",
         drop: function (event, ui) {
             $(this).find(".placeholder").remove();
             $("<li></li>").text(ui.draggable.text()).appendTo(this);
         }
     }).sortable({
         items: "li:not(.placeholder)",
         sort: function () {
             $(this).removeClass("ui-state-default");
         }
     });
 });
Run Code Online (Sandbox Code Playgroud)

UDB*_*UDB 23

使用droppable's drop活动的callback比较current top offset position of the draggable helpertop offset每一个元素已经存在或以前在加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);
    }

}

} 
Run Code Online (Sandbox Code Playgroud)

带代码的演示

全屏演示


ted*_*947 17

这样做怎么样?我认为使用connectToSortable和connectWith选项都可以.隐藏/显示占位符可能有更聪明的方法,但这绝对有效.

$(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();
            }
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

小提琴中的工作演示