搜索

首页  >  问答  >  正文

JavaScript实现多个元素的拖放功能

我找到了这段代码,它可以让你在特定区域内拖放一个项目,但我无法重写它,以便允许多个元素拖放,因为我不知道如何从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粉276064178P粉276064178312 天前481

全部回复(1)我来回复

  • P粉460377540

    P粉4603775402024-01-11 12:57:46

    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>

    回复
    0
  • 取消回复