JQuery拖放删除可排序的连接列表

时间:2015-04-29 07:17:10

标签: jquery jquery-ui drag-and-drop jquery-ui-sortable

JQueryUI demos上的示例开始我试图禁用左侧列表中的排序,并且左侧的项目必须复制而不能移动,  是否有可能以某种方式?

I've created a jsfiddle for it

$(function() {
    $( "#sortable1, #sortable2" ).sortable({
      connectWith: ".connectedSortable"
    }).disableSelection();
});

通过使用可拖动和可放置的交互,我可以更接近,但我无法将元素放到特定位置,就像我可以使用sortable(jsfiddle here):

$(function() {

    $( "#sortable1 li" ).draggable({
        appendTo: "body",
        helper: "clone"
    });
    $( "#sortable2" ).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" );
        }
    });
});

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。以下是修复代码:

$(function() {

    $( "#sortable1 li" ).draggable({
        appendTo: "body",
        helper: "clone"
    });
    $( "#sortable2" ).droppable({
        activeClass: "ui-state-default",
        hoverClass: "ui-state-hover",
        accept: ":not(.ui-sortable-helper)",
        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);
                }
            }
        }
    }).sortable({
        items: "li:not(.placeholder)",
        sort: function() {
            $( this ).removeClass( "ui-state-default" );
        }
    });
});