返回列表

HTML5新特性Drag&Drop

默认分类 2017/10/07 06:17

示例如下:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>html5 drag &amp; drop 拖拽与拖放测试</title>
</head>

<body>
  <div class="dustbin">垃圾箱</div>
  <br/>
  <div class="dragbox">
    <div class="draglist" title="拖拽我" draggable="true">列表1</div>
    <div class="draglist" title="拖拽我" draggable="true">列表2</div>
    <div class="draglist" title="拖拽我" draggable="true">列表3</div>
    <div class="draglist" title="拖拽我" draggable="true">列表4</div>
    <div class="draglist" title="拖拽我" draggable="true">列表5</div>
    <div class="draglist" title="拖拽我" draggable="true">列表6</div>
  </div>
  <div class="dragremind"></div>
  <script>

  var eleDrag = null

  document.querySelectorAll('.draglist').forEach(function(elem) {
    elem.onselectstart = function() {
      return false
    }
    elem.ondragstart = function(ev) {
      ev.dataTransfer.effectAllowed = 'move'
      ev.dataTransfer.setData('text', ev.target.innerHTML)
      ev.dataTransfer.setDragImage(ev.target, 0, 0)
      eleDrag = ev.target
      return true
    }
    elem.ondragend = function(ev) {
      ev.dataTransfer.clearData('text')
      eleDrag = null
      return false
    }
  })

  var eleDustbin = document.querySelectorAll('.dustbin')[0]
  eleDustbin.ondragover = function(ev) {
    ev.preventDefault()
    return true
  }
  eleDustbin.ondragenter = function(ev) {
    this.style.color = 'red'
    return true
  }
  eleDustbin.ondragleave = function(ev) {
    this.style.color = 'black'
    return true
  }
  eleDustbin.ondrop = function(ev) {
    if (eleDrag) {
      document.querySelectorAll('.dragremind')[0].innerHTML += '<br/><strong>"' + eleDrag.innerHTML + '"</strong>被扔进了垃圾箱'
      eleDrag.parentNode.removeChild(eleDrag)
    }
    this.style.color = 'black'
    return false
  }
  </script>
</body>

</html>