【问题标题】:Jquery UI Draggable element top issue due to position relativeJquery UI Draggable element top问题由于位置相对
【发布时间】:2020-06-06 12:28:06
【问题描述】:

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

然而,动态创建的可拖动元素相对定位自己,第二个元素总是给出不想要的css topleft值,因为它与第一个元素有关。

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

这是一个 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;
        }

       }

    });
  });

【问题讨论】:

标签: jquery css jquery-ui


【解决方案1】:

考虑以下示例。

$(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

查看更多:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多