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

我正在开发一个项目,我将元素从第三方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(); $("
  • ").text(ui.draggable.text()).appendTo(this); } }).sortable({ items: "li:not(.placeholder)", sort: function () { $(this).removeClass("ui-state-default"); } }); });

    使用droppable's drop事件的callback来比较current top offset position of the draggable helpercurrent top offset position of the draggable helper与已经存在或之前添加到droppable的每个元素的top offset

     drop: function (event, ui) { if($(this).find(".placeholder").length>0) //add first element when cart is empty { $(this).find(".placeholder").remove(); $("
  • ").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 { $("
  • ").text(ui.draggable.text()).insertBefore($(this)); i=1; return false; //break loop } }) if(i!=1) //if element dropped at the end of cart { $("
  • ").text(ui.draggable.text()).appendTo(this); } } }

    带代码的演示

    全屏演示

    这样做怎么样? 我认为使用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(); } } }); }); 

    小提琴中的工作演示