By HTML5 drag and drop API, to achieve a simple picture drag and drop effect.

HTML5 drag and drop API

First we need to know how elements can be dragged and dropped. We need to set their draggable attribute. The img and A tags’ dragable attribute is true by default and does not need to be set manually.

The drag-and-drop API listens for the following events:

  • Dragstart: source object drag starts;
  • Drag: the source object is being dragged;
  • Dragend: source object drag ends;
  • Dragenter: Enters the procedure object area;
  • Dragover: moves within the process object area;
  • Dragleave: leaves the process object area;
  • Drop: Drop the source object to the target area.

For these events, preventDefault() is required to cancel the default behavior.

In drag-and-drop events, dataTransfer is provided to transfer data between source and target objects. DataTransfer is usually called by E.datatransfer. DataTransfer methods are as follows:

  • setData(format, data)
  • GetData (format);
  • ClearData ().

&esmp; These are the basics. Instead of listening to my BB, open MDN and type a few lines of code.

Two, easy picture drag sort.

Let’s start with the image:

Let’s start by looking at our DOM structure

    <! -- Some tags -->div#drag-wrap div(class="item" id="wrap1") img(id="img1") ... .Copy the code

Events we need to listen for:

    const dragCon = document.getElementById('drag-wrap');

    dragCon.addEventListener('dragstart', startDrag, false);

    /** * the default behavior of dragover must be prevented, otherwise the drop */ will not be triggered
    dragCon.addEventListener('dragover'.function (e) {
        e.preventDefault();
    }, false);
    dragCon.addEventListener('drop', exchangeElement, false);
Copy the code

In the dragstart event, we need to remember which child and parent elements we want to swap:

    function startDrag(e) {
        e.dataTransfer.setData('Text', e.target.id + '; ' + e.target.parentElement.id);
    }
Copy the code

The most important thing is to deal with the logic of our exchange elements and some edge condition judgments in the DROP event.

    function exchangeElement(e) {
        e.preventDefault();
        const el = e.target;
        let PE, // The parent of the position to be inserted
            CE; // The element to be swapped
        if(el.tagName.toLowerCase() ! = ='div') {                     PE = el.parentElement;
            CE = el;
        } else {
            PE = el;
            CE = el.querySelector('img');
        }

        /** ** the error is not in control */
        if(! PE.classList.contains('item')) {
            return;
        }
        const data = e.dataTransfer.getData('Text').split('; ');
        // Swap elements
        document.getElementById(data[1]).appendChild(CE);
        PE.appendChild(document.getElementById(data[0]));
    }
Copy the code

If you like this article, please pay attention to my subscription number. I love typing code and check out more content.