JavaScript實作多個元素的拖放功能
P粉276064178
P粉276064178 2024-01-10 16:54:21
0
1
514

我找到了這段程式碼,它可以讓你在特定區域內拖放一個項目,但我無法重寫它,以便允許多個元素拖放,因為我不知道如何從drop_handler函數中獲取拖曳對象的id。

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>

P粉276064178
P粉276064178

全部回覆(1)
P粉460377540

onDragStart中,「儲存」dragElement。這樣你就可以在drop_handler中使用這個變數來移動物品。

我為dropElement新增了一個const,因為它不會改變。

let offsetX;
let offsetY;
let dragElement = null;
const dropElement = document.getElementById("id-drop");

onDragStart = function(ev) {
  const rect = ev.target.getBoundingClientRect();

  offsetX = ev.clientX - rect.x;
  offsetY = ev.clientY - rect.y;
  
  dragElement = ev.target;
};

drop_handler = function(ev) {
  ev.preventDefault();

  const left = parseInt(dropElement.style.left);
  const top = parseInt(dropElement.style.top);

  dragElement.style.position = 'absolute';
  dragElement.style.left = ev.clientX - left - offsetX + 'px';
  dragElement.style.top = ev.clientY - top - offsetY + 'px';
  dropElement.appendChild(dragElement);
};

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 #1</div>

<div id="id2" draggable="true" ondragstart="onDragStart(event)" style="border:2px solid green; cursor:pointer;width:100px;height:50px;">拖动的Div #2</div>

<div id="id-drop" 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>
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板