简体   繁体   中英

How to shift elements with Drag and Drop by using HTML5?

I'm working with Drag and Drop tutorial from HTML Rocks. The current tutorial basically does a switch of the dragged element and the element it is dropped on. What was in point A goes to point B and point B goes to point A.

|A|B|C|  -->  |B|A|C|
|D|E|F|       |D|E|F|

I'm trying to change this logic. If I drag point E, it should be in between the others.

|A|B|C|  -->  |A|E|B|
|D|E|F|       |C|D|F|

This is the demo I have for this.

Should this be done changing the property dropEffect or it will be necessary to create a new div for adding the item we're moving?

function handleDragStart(e) {
  this.style.opacity = '0.4';  // this / e.target is the source node.
}

function handleDragOver(e) {
  if (e.preventDefault) {
    e.preventDefault(); // Necessary. Allows us to drop.
  }

  e.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.

  return false;
}

I found the way to do this thanks to @tbirell

I'm using the Jquery UI library for this and change all the logic of what I did at the beginning

Instead of using DIV, I'm replacing them by UL and LI

<ul id="sortable">
  <li class=" ui-state-default">Item 1</li>
  <li class=" ui-state-default">Item 2</li>
  <li class=" ui-state-default">Item 3</li>
  <li class=" ui-state-default">Item 4</li>
  <li class=" ui-state-default">Item 5</li>
  <li class=" ui-state-default">Item 6</li>
</ul>

The library is the one that manages the logic of this.

$( function() {
    $( "#sortable" ).sortable({
      revert: true
    });
    $( "#draggable" ).draggable({
      connectToSortable: "#sortable",
      helper: "clone",
      revert: "invalid"
    });
    $( "ul, li" ).disableSelection();
  } );

A link of the working demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM