开发者

jQuery draggable can still drop on empty - how do I stop it?

开发者 https://www.devze.com 2023-02-18 12:08 出处:网络
If I have a jQuery Draggable object $(\'#drag-me\').draggable({ helper: \'clone\', connectToSortable: \'#sortable\'

If I have a jQuery Draggable object

$('#drag-me').draggable({
  helper: 'clone',
  connectToSortable: '#sortable'
});

and a开发者_Go百科 connected sortable

$('#sortable').sortable({
  receive: performMagic
});

I can't prevent this draggable from dropping on the empty sortable.

Sortable itself has an option dropOnEmpty, which, when set to false, prevents you dropping things from that sortable onto an empty sortable; but Draggable doesn't have such an option.

I tried this:

$('#sortable').sortable({
  start: function(e, ui) {
    if (ui.item[0].nodeName == 'IMG') {
       $(this).sortable('cancel')
     }
  }
});

In my case the #drag-me element is an image but the Sortable elements are not. The performMagic function is successfully converting the image into the TBODY element that the sortable comprises. But results were inconsistent; sometimes it would successfully cancel the operation but other times it would break in other places.

The question is, am I on the right track? Is this the only way of preventing a Draggable from being dropped on an empty linked Sortable? Is there a way I can hijack the existing Sortable-to-Sortable behaviour?

TIA Al


Can you check whether the sortable is empty in the receive event? Something like:

$('#sortable').sortable({
  receive: function(event, ui) { 
    if ($('#sortable').children().length > 0) {
        // PerformMagic...
    }
  }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消