The first way: using the API dataTransfer H5
Realization of ideas:
1. drag element is set to be allowed to drag and drop, and impart dragstart event id into a converted data storage;
2. Add a container dragover property to add an event to prevent the browser's default event, allowing the placement of elements, and give drop events to place elements.
code show as below:
<html> <head> <meta charset="utf-8"> <style> .box1 { width: 100px; height: 100px; border: 1px black solid; margin-bottom: 20px; background: lightblue; } .box2 { width: 100px; height: 100px; border: 1px black solid; background: lightcoral; } </style> </head> <body> <!-- 参数要传入event对象 --> <div class="box1" ondragover="allowdrop(event)" ondrop="drop(event)"> <img src="img/2.jpg" alt="00" draggable="true" ondragstart="drag(event)" id="drag" = e.dataTransfer.getData("text"); e.target.appendChild(document.getElementById(data)); } function drag(e) { e.dataTransfer.setData("text", e.target.id); } </script> </body> </html>
The second way: use native JS (binding achieved by locating the position calculating element)
Ideas:
1. Get the mouse and the distance from the left edge of the boundary elements;
2. After calculating the relative distance moved relative positions of elements of the original, imparting style.
<html> <head> <meta charset="utf-8"> <style> .box1 { width: 100px; height: 100px; border: 1px black solid; margin-bottom: 20px; background: lightblue; } .box2 { width: 100px; height: 100px; border: 1px black solid; background: lightcoral; } #drag { position: relative; } </style> </head> <body> <div class="box1" id="drag"> <span>我是盒子一</span> </div> <div class="box2"> < Span > I cassette two </ span > </ div > < Script > the let Drag = document.querySelector ( " #drag " ); // get operation element drag.onmousedown = function (E) { // mouse press triggered var disx = e.pageX - drag.offsetLeft; // Get the mouse relative elemental distance var DISY = e.pageY - drag.offsetTop; the console.log (e.pageX); the console.log (drag.offsetLeft); document.onmousemove = function (E) { // mouse movement triggering event, the corresponding element is moved to a position drag.style.left = e.pageX - disx + ' PX ' ; drag.style.top = e.pageY - DISY + ' PX ' ; } document.onmouseup = function () { // mouse lifted clear of the binding event, the element is placed in a position corresponding to document.onmousemove = null ; document.onmousedown = null ; }; e.preventDefault (); // stop the default event browser }; </ Script > </ body > </ HTML >