Native JS realizes drag and drop function

  • 2021-10-13 06:34:54
  • OfStack

In this paper, we share the specific code of JS to realize drag and drop function for your reference. The specific contents are as follows

Principle of drag and drop: 3 events onmousedown, onmousemove and onmousemove

1. When the mouse is pressed down, onmousedown is triggered to obtain mouse coordinates x and y, and element coordinates x and y are obtained

Obtain the coordinates of the mouse position through event. clientX, event. clientY


let x = e.clientX - box.offsetLeft; // The distance between the mouse click coordinates and the left edge of the box 
let y = e.clientY - box.offsetTop; // The distance between the mouse click coordinate and the upper edge of the box 

2. Set the values of elements left and top (position: absolute should be set for elements)


box.style.left = ev.clientX - x + 'px';
box.style.top = ev.clientY - y + 'px';

3. Release the mouse to cancel the dom event

The following is the detailed code: I only opened the lateral movement


<!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>
 #box {
 width: 100px;
 height: 100px;
 background: red;
 position: absolute
 }
 
 </style>
</head>
 
<body style="position: relative;overflow: hidden;">
 <div id="box">
 
 </div>
 
 <script>
 window.onload = function () {
 let box = document.getElementById('box')
 box.onmousedown = function (ev) {
 let e = ev || event;
 let x = e.clientX - box.offsetLeft; // The distance between the mouse click coordinates and the left edge of the box 
 let y = e.clientY - box.offsetTop; // The distance between the mouse click coordinate and the upper edge of the box 
 document.onmousemove = function (ev) {
  let e = ev || event;
  box.style.left = ev.clientX - x + 'px';
  box.style.top = ev.clientY - y + 'px';
  
  let bodyScreenX = ev.screenX
  let bodyClientWidth = document.body.clientWidth
  
  document.onmouseup = function (ev) {
  if (ev.clientX - x < 0) {
  box.style.left = 0
  } else if (bodyScreenX > bodyClientWidth) {
  box.style.right = 0
  box.style.left = bodyClientWidth - 100 + 'px'
  }
  document.onmousemove = null;
  document.onmouseup = null;
  }
 }
 }
 }
 
 </script>
</body>
 
</html>

Related articles: