Jquery UI 可拖动元素由于位置相对而出现顶部问题

Jquery UI Draggable element top issue due to position relative

我在我的一个项目中使用 jquery UI,我在其中获取拖动项目的坐标,然后使用它在 canvas 上绘制文本。

但是 动态 创建了 可拖动元素 相对定位,第二个元素总是给出不需要的 css topleftvalue,因为它与第一个元素相关。

有没有办法改变位置 属性 或任何其他方法来实现与父级相关的顶部和左侧值。

这是一个 codepen ,当我拖动到当前位置。

设置可拖动组件:

$(function() {
    $( ".drag" ).draggable({
       containment: ".container",
       scroll: false,
       drag: function() {
         let top = $(this).css("top");
        let left = $(this).css("left");
      let index = $(this).data("index");   
        if(index == "1") {
          document.getElementById("one").innerText = "top: " + top + " left:" + left;
        }else {
           document.getElementById("two").innerText = "top: " + top + " left:" + left;
        }

       }

    });
  });

考虑以下示例。

$(function() {
  $(".drag").draggable({
    containment: ".container",
    scroll: false,
    drag: function(e, ui) {
      var self = $(this);
      var parent = $(".container");
      var pos = self.position();
      // Adjust for position of parent and border, gives Inner position
      pos.left = pos.left - parent.offset().left - 2;
      pos.top = pos.top - parent.offset().top - 2;
      $("#" + self.data("index")).html("top: " + pos.top + " left:" + pos.left);
    }
  });
});
.container {
  width: 500px;
  height: 300px;
  border: 2px red solid;
  margin: 4rem auto;
  margin-bottom: 10px;
}

.drag {
  background: orange;
  color: white;
  width: 100px;
  height: 100px;
  line-height: 100px;
  white-space: nowrap;
  text-align: center;
  cursor: move;
  &:hover {
    background: darken(orange, 5);
  }
}

h5, p {
  margin: 0;
}
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="container">
  <div id="draggable-1" data-index="one" class="drag">
    <p>One</p>
  </div>
  <div id="draggable-2" data-index="two" class="drag">
    <p>two</p>
  </div>
</div>
<div class="info">
  <h5> 1st element: </h5>
  <p id="one"></p>
  <br/>
  <h5> 2nd element: </h5>
  <p id="two"></p>
</div>

使用拖动的元素.position(),我们可以看到它在页面上相对于0,0topleft。我们只需要根据容器的位置调整它。 .offset() 将给出 topleft 的实际分数,因为元素有边距。 .position() 会报告它位于页面上的 0,0

查看更多: