Tutorial for HTML5 drag&drop - sortable list

前端 未结 4 1462
攒了一身酷
攒了一身酷 2021-01-30 21:37

Do anyone know a really good tutorial for HTML5 drag&drop? Im making a toDo-list and I want to be able to reorder/sort it with this API. I\'ve been googling for it like a ma

4条回答
  •  無奈伤痛
    2021-01-30 22:18

    I've tried to keep this sample as simple as possible.

    If you create a HTML list:

    • Apples
    • Oranges
    • Bananas
    • Strawberries

    ...and the following javascript:

    var _el;
    
    function dragOver(e) {
      if (isBefore(_el, e.target))
        e.target.parentNode.insertBefore(_el, e.target);
      else
        e.target.parentNode.insertBefore(_el, e.target.nextSibling);
    }
    
    function dragStart(e) {
      e.dataTransfer.effectAllowed = "move";
      e.dataTransfer.setData("text/plain", null); // Thanks to bqlou for their comment.
      _el = e.target;
    }
    
    function isBefore(el1, el2) {
      if (el2.parentNode === el1.parentNode)
        for (var cur = el1.previousSibling; cur && cur.nodeType !== 9; cur = cur.previousSibling)
          if (cur === el2)
            return true;
      return false;
    }
    

    ... you should get a sortable list.

    You can try the code on https://codepen.io/crouchingtigerhiddenadam/pen/qKXgap

    Please be aware of the following bug in FireFox: https://developer.mozilla.org/en-US/docs/Web/Events/dragenter

    Hope this helps.

提交回复
热议问题