Drag&Drop 拖拉效果

設定拖拉元件 draggable=’true’
<div class='parent'>
  <span id='draggableSpan' draggable='true' ondragstart='onDragStart(event);'>
    draggable
  </span>
  <span ondragover='onDragOver(event);' ondrop='onDrop(event);'> dropzone </span>
</div>
事件
  • ondragstart
  • ondragover
  • ondrop
開始拖拉 ondragstart
function onDragStart(event) {
  event.dataTransfer.setData('text/plain', event.target.id);

  event.currentTarget.style.backgroundColor = 'yellow';
}
拖拉中 ondragover
function onDragOver(event) {
  event.preventDefault();
}
結束拖拉(放掉滑鼠) ondrop
function onDrop(event) {
  const id = event.dataTransfer.getData('text');

  const draggableElement = document.getElementById(id);
  const dropzone = event.target;
  
  dropzone.appendChild(draggableElement);

  event.dataTransfer.clearData();
}