Jquery UI可拖动元素顶部的问题,因为位置相对。

问题描述 投票:0回答:1

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

然而,我在项目中使用jquery用户界面,获取被拖动项目的坐标,然后用它在画布上绘制文字。动态 创建 可拖动元素 的相对位置,而第2个元素总是给人不想要的css。顶端左边值,因为它与第1个元素有关。

有什么方法可以改变位置属性或其他方法来实现与父元素相关的顶部和左侧的值。

下面是一个 密码笔 在这里你可以看到,当我拖动到当前位置以上时,第2个元素给出了负顶值。

设置可拖动组件。

$(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个回答
0
投票

请看下面的例子。

$(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(),我们可以看到它的 topleft 与...相对 0,0 在页面上。我们只需要根据容器的位置进行调整。.offset() 将给出实际的点 topleft 因为该元素有一个margin。.position() 会报告它在 0,0 在页面上。

查看更多。

© www.soinside.com 2019 - 2024. All rights reserved.