如何找到可拖放元素相对于可拖放区域的位置?

How do I find the position of the draggable element relative to the droppable area

本文关键字:拖放 位置 区域 元素 何找 相对于      更新时间:2023-09-26

我使用的是HTML5原生拖放。

我有问题找到可拖动元素相对于它的父容器的位置。

任务摘要

我有一个"position: relative"div,我认为它是一个"可拉区域"。在这个div中,我有几个"position: absolute"图像元素,我将它们标记为可拖动的。我希望这些图像可以被用户自由移动。

为了设置元素的位置,我在'dragend'上设置了一个侦听器。

结束top/left变量必须基于百分比,而不是像素。

<<p> 当前尝试/strong>

下面你可以看到我的尝试:

draggable.addEventListener('dragend', function (event) {
event.preventDefault();
//Gets the position of the two elements relative to the viewport
var droppableBoundingRect = droppable.getBoundingClientRect();
//Establishes the percentage using the droppable height and width
var draggableXPercentage = ((event.clientX - droppableBoundingRect.left) / droppable.clientWidth) * 100;
var draggableYPercentage = ((event.clientY - droppableBoundingRect.top) / droppable.clientHeight) * 100;
//Set the positional elements of the draggable element
event.target.style.top = draggableYPercentage + "%";
event.target.style.left = draggableXPercentage + "%";
}, false);

这里是我希望工作的JSFiddle,注释显示了我期望每个片段做什么:

https://jsfiddle.net/oL8yd9Lr/

也许我在错误的森林里找错了树。

找到一个可能的解决方案。它不是完美的,但应该说明你如何得到相对位置。我可能有点过分了,但我已经评论了重要的部分。

小提琴

;
(function($, undefined) {
  var dragging;
  $(function() {
    $('.dropzone').on({
      'dragover dragenter': dragover,
      'drop': drop
    }).on({
      'dragstart': dragstart,
      'dragend': dragend
    }, '.drag');
  });
  function dragstart(e) {
    e.stopPropagation();
    var dt = e.originalEvent.dataTransfer;
    if (dt) {
      dt.effectAllowed = 'move';
      dt.setData('text/html', '');
      dragging = $(this);
      // Set the position of the mouse relative to the element at 0,0
      dt.setDragImage(dragging.get(0), 0, 0);
    }
  }
  function dragover(e) {
    e.stopPropagation();
    e.preventDefault();
    var dt = e.originalEvent.dataTransfer;
    if (dt && dragging) {
      dt.dropEffect = 'move';
      dragging.hide(); // Hide the element while dragging
    }
    return false;
  }
  function drop(e) {
    e.stopPropagation();
    e.preventDefault();
    if (dragging) {
      var dropzone = $(this);
      // Get the offset of the dropzone relative to the window
      var offset = dropzone.offset();
      // Set the offset of the drag relative to the dropzone
      dragging.css({
        'top': e.clientY - offset.top,
        'left': e.clientX - offset.left
      });
      dragging.trigger('dragend'); // Trigger the dragend
    }
    return false;
  }
  function dragend(e) {
    if (dragging) {
      dragging.show();
      dragging = undefined;
    }
  }
}(jQuery));