jQuery UI draggable element dropped into sortable

2019-04-29 01:39发布

I have a list of draggable items, and I wish to be able to drag them onto a sortable content block. Here’s my markup:

<div class='items'>
    <div class="one">One</div>
    <div class="two">Two</div>
</div>

<div class="content">
    <div class="block">Foo</div>
    <div class="block">Bar</div>
</div>

The thing is, that I want the dragged item to "become" a block as soon as the dragging starts and remain a block when it’s dropped. I have tried this:

$('.items div').draggable({
    helper: function(e) {
        return $('<div>').addClass('block').text( $(e.target).text() );
    },
    connectToSortable: ".content"
});

$('.content').sortable();​

Fiddle: http://jsfiddle.net/MF4qu/

But even if I create a custom helper that looks like a block, it reverts back to the original dragged element as soon as it’s dropped. Does anyone know how to properly insert a block in my example page? I already looked through the UI API but I can’t figure it out.

1条回答
混吃等死
2楼-- · 2019-04-29 02:35

When the draggable element is dropped into sortable, it triggers the sortable update event. One solution is to listen to that event, and turn the dropped item into a block:

$('.items div').draggable({
    helper: function(e) {
        return $('<div>').addClass('block').text( $(e.target).text() );
    },
    connectToSortable: ".content"
});

$('.content').sortable({
    update: function (event, ui) {
        ui.item.addClass('block');
    }
});​

Working demo: http://jsfiddle.net/DaXuT/1/

查看更多
登录 后发表回答