Home  >  Article  >  Web Front-end  >  How to implement box drag and drop effect in JS? (with code)

How to implement box drag and drop effect in JS? (with code)

青灯夜游
青灯夜游forward
2020-06-16 10:31:293070browse

How to implement box dragging effect in JS? This article will give you a detailed introduction to the JS method to achieve the box drag effect. The sample code in the article is introduced in great detail. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

html code:

<!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>拖拽</title>
<body>
  <p class="leftBox"></p>
  <p class="rightBox">
    <!-- 开启拖拽属性draggable -->    
    <p class="circle" draggable="true"></p>
  </p>
</body>
 
</html>

css code:

<style>
    .leftBox {
      display: inline-block;
      width: 100px;
      height: 100px;
      border: 1px solid black;
      border-radius: 10px;
      position: relative;
    }
 
    .rightBox {
      display: inline-block;
      width: 100px;
      height: 100px;
      border: 1px solid black;
      border-radius: 10px;
      position: relative;
    }
 
    .circle {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      background: radial-gradient(25px at center, white, skyblue);
      /* 绝对居中 */
      position: absolute;
      left: 50%;
      margin-left: -25px;
      top: 50%;
      margin-top: -25px;
    }
  </style>

js code:

<script>
  //获取dom元素,分别是左盒子 圆圈 右盒子
  var leftBox = document.querySelector(&#39;.leftBox&#39;);
  var circle = document.querySelector(&#39;.circle&#39;);
  var rightBox = document.querySelector(&#39;.rightBox&#39;);
  var text = document.querySelector(&#39;.text&#39;);
 
  //移动circle
  circle.
 
  //开启左盒子的移入事件
  leftBox.ondragover = function (event) {
    event.preventDefault();
  }
  leftBox.ondrop = function () {
    leftBox.appendChild(circle);
  }
 
  //开启右盒子的移入事件
  rightBox.ondragover = function (event) {
    event.preventDefault();
  }
  rightBox.ondrop = function () {
    rightBox.appendChild(circle);
  }
 
</script>

Effect:

Instructions:

Regarding the usage of events, the official uses object.addEventListener("dragover", myScript) and event.target.id

For more jQuery and Javascript special effects, it is recommended to visit: js special effects collection!

The above is the detailed content of How to implement box drag and drop effect in JS? (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete