原生js实现拖拽替换

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    div {
      width: 100px;
      height: 100px;
      text-align: center;
      line-height: 100px;
      border: 1px solid red;
      margin-right: 15px;
    }
  </style>
</head>

<body>
  <div class="d1" draggable="true">div1</div>
  <div draggable="true" class="d2">div2</div>
  <div draggable="true" class="d3">div3</div>
  <div draggable="true" class="d4">div4</div>
  <div draggable="true" class="d5">div5</div>
</body>
<script>
  var div = document.getElementsByTagName('div')
  var container = null; // 存放拖拽元素的容器
  for (let i = 0; i < div.length; i++) {
    // 开始拖拽时把元素用容器存放
    div[i].ondragstart = function () {
      container = this;
    }
    // 默认当我dragover的时候会阻止我做drop操作,这里取消默认事件
    div[i].ondragover = function (e) {
      e.preventDefault()
    }
    // 当拖动结束的时候,给拖动的div所在位置的下面的div做drop事件
    div[i].ondrop = function () {
      if (container != null && container != this) {
        let temp = document.createElement('div')
        document.body.replaceChild(temp, this)
        document.body.replaceChild(this, container)
        document.body.replaceChild(container, temp)
      }
    }
  }
</script>

</html>

  

猜你喜欢

转载自www.cnblogs.com/webSong/p/12437042.html