I found this code that allows you to drag and drop an item within a specific area, but I can't rewrite it to allow multiple elements to be dragged and dropped because I don't know how to get the drag from the drop_handler function The id of the object.
let offsetX; let offsetY; onDragStart = function(ev) { const rect = ev.target.getBoundingClientRect(); offsetX = ev.clientX - rect.x; offsetY = ev.clientY - rect.y; }; drop_handler = function(ev) { ev.preventDefault(); const left = parseInt(id2.style.left); const top = parseInt(id2.style.top); id1.style.position = 'absolute'; id1.style.left = ev.clientX - left - offsetX + 'px'; id1.style.top = ev.clientY - top - offsetY + 'px'; id2.appendChild(document.getElementById("id1")); }; dragover_handler = function(ev) { ev.preventDefault(); ev.dataTransfer.dropEffect = "move"; };
<div id="id1" draggable="true" ondragstart="onDragStart(event)" style="border:2px solid green; cursor:pointer;width:100px;height:50px;">拖动的Div</div> <div id="id2" style="position:absolute;left:200px;top:50px;border:2px solid red; cursor:pointer;width:200px;height:200px;" ondrop="drop_handler(event)" ondragover="dragover_handler(event)">放置的Div </div>
In
onDragStart
, "save"dragElement
. This way you can use this variable indrop_handler
to move items.I added a
const
todropElement
because it won't change.