jQuery draggable and droppable between two containers and sortable

大兔子大兔子 提交于 2019-11-28 03:58:48
GR7

Here's the fiddle with the final result:

http://jsfiddle.net/39khs/82/

The key was to handle the "drop" event and manually removing the dropped image from #origin and add it to #drop. That is actually what I was doing on the first implementation, but did not know how to do it exactly with jQuery:

 $(dropped).detach().css({top: 0,left: 0}).appendTo(droppedOn);

I am not sure why jQuery does not really remove the dragged element from the old container and add it to the new one, but that is what had to be done for the newly dropped item to display correctly and not just exactly where it was dropped, disregarding css placing/styling.

The key line was by @Barry Pitman on the following SO question:

jQuery draggable + droppable: how to snap dropped element to dropped-on element

UPDATE: I had some spare time today and wanted to check if it was possible with just sortable, and lo and behold, it was.

http://jsfiddle.net/wj4ak/5/

just two lines of code allow dragging and dropping from one container to another, and sorting the items. They do not need to be inside ul/ol lists at all. The one annoying thing is that I did not intend to make the items on the origin div sortable, but it's something I can live with for now.

If you want to use .droppable(), .draggable(), & .sortable(), then you only need to use .sortable().

Using your jsfiddle, I made the following changes:

HTML:

<div id="wrapper">
    <div id="origin" class="fbox">
    <ul id="sort1" class="list">
      <li><img src="http://placehold.it/140x100" id="one" title="one" class="draggable" /></li>
      <li><img src="http://placehold.it/140x100" id="two" title="two" class="draggable" /></li>
      <li><img src="http://placehold.it/140x100" id="three" title="three" class="draggable" /></li>
    </ul>
    </div>
  <p>test</p>
    <div id="drop" class="fbox">
      <ul id="sort2" class="list"></ul>
    </div>
</div>

JAVASCRIPT:

$( "#sort1, #sort2" ).sortable({
      helper:"clone", 
      opacity:0.5,
      cursor:"crosshair",
      connectWith: ".list",
      receive: function( event, ui ){ //this will prevent move than 3 items in droppable list
         if($(ui.sender).attr('id')==='sort1' && $('#sort2').children('li').length>3){
           $(ui.sender).sortable('cancel');
         }
      }
});

$( "#sort1,#sort2" ).disableSelection();

CSS:

#origin
{
  background-color: green;
}
#drop
{
  background-color: red;
  min-height: 120px;
}
.list
{ 
  min-height: 120px;
} 
.list li
{
 display: inline-block;
 list-style-type: none;
 padding-right: 20px;
}

DEMO: http://jsfiddle.net/39khs/80/

Hope this helps and let me know if you have any questions!


Links:
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!