html5 drag API 实现列表拖拽

抛开兼容性,HTML5 提供的一系列 API 可以简化很多代码量。

最终效果:

<ul id="columns">
  <li class="column" draggable="true"><header>A</header></li>
  <li class="column" draggable="true"><header>B</header></li>
  <li class="column" draggable="true"><header>C</header></li>
  <li class="column" draggable="true"><header>D</header></li>
  <li class="column" draggable="true"><header>E</header></li>
</ul>
function addDnDHandlers(elem) {
  elem.addEventListener('dragstart', handleDragStart, false); //拖拽元素开始被拖拽的时候触发的事件,此事件作用在被拖曳元素上
  elem.addEventListener('dragenter', handleDragEnter, false) //当拖曳元素进入目标元素的时候触发的事件,此事件作用在目标元素上
  elem.addEventListener('dragover', handleDragOver, false); //拖拽元素在目标元素上移动的时候触发的事件,此事件作用在目标元素上
  elem.addEventListener('dragleave', handleDragLeave, false); //拖拽元素离开目标元素上移动的时候触发的事件,此事件作用在目标元素上
  elem.addEventListener('drop', handleDrop, false); //被拖拽的元素在目标元素上同时鼠标放开触发的事件,此事件作用在目标元素上
  elem.addEventListener('dragend', handleDragEnd, false); //当拖拽完成后触发的事件,此事件作用在被拖曳元素上
}

var cols = document.querySelectorAll('#columns .column');
[].forEach.call(cols, addDnDHandlers); //为每个元素绑定drop事件
function handleDragStart(e) {
  // Target (this) element is the source node.
  dragSrcEl = this;
  //设置拖拽效果
  e.dataTransfer.effectAllowed = 'move';
  e.dataTransfer.setData('text/html', this.outerHTML);
  //被拖拽的元素添加class
  this.classList.add('dragElem');
}
function handleDragEnter(e) {
  // this / e.target is the current hover target.
}
function handleDragOver(e) {
  if (e.preventDefault) {
    e.preventDefault(); // Necessary. Allows us to drop.
  }
  this.classList.add('over');

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

  return false;
}
function handleDragLeave(e) {
  this.classList.remove('over');  // this / e.target is previous target element.
}

在拖拽过程中蓝色的线条是一个边框,利用拖拽事件添加class 并设置css就能有“响应”式的效果。

拖拽释放,进行html的替换。

function handleDrop(e) {
  // this/e.target is current target element.

  if (e.stopPropagation) {
    e.stopPropagation(); // Stops some browsers from redirecting.
  }

  // Don't do anything if dropping the same column we're dragging.
  if (dragSrcEl != this) {
    // Set the source column's HTML to the HTML of the column we dropped on.
    //alert(this.outerHTML);
    //dragSrcEl.innerHTML = this.innerHTML;
    //this.innerHTML = e.dataTransfer.getData('text/html');
    this.parentNode.removeChild(dragSrcEl);
    var dropHTML = e.dataTransfer.getData('text/html');
    this.insertAdjacentHTML('beforebegin',dropHTML);
    var dropElem = this.previousSibling;
    addDnDHandlers(dropElem);
    
  }
  this.classList.remove('over');
  return false;
}
function handleDragEnd(e) {
  // this/e.target is the source node.
  this.classList.remove('over');

  /*[].forEach.call(cols, function (col) {
    col.classList.remove('over');
  });*/
}