拖动

时间:2017-03-23 09:37:08

标签: jquery jquery-ui position draggable

我正在尝试使用jQuery UI获取多个可拖动元素的位置。我发现了一个类似的问题(X and Y Positions of multiple jQuery UI Elements),但在我的情况下,有一个div有多个可拖动的div,所以答案对我不起作用。

$('#snaptarget').each(function() {
  var elems = $(this).find('div');
  elems.draggable({
    containment: '#snaptarget',
    scroll: false,
    grid: [5, 5],
    drag: function() {
      var links = Math.round(elems.position().left) / 20;
      var oben = Math.round(elems.position().top) / 20;
      $(this).find('span').html('Links: ' + links + 'mm<br>Oben: ' + oben + 'mm');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id="snaptarget" style="background: green;height: 1720px; width: 1720px; position: absolute;margin: 20mm;">
  <div id="ci1" style="z-index: 999; position: absolute; overflow: hidden; width: 140px; height: 140px; background-color:white;border: 1px solid red;">
    <p>id: ci1<br>
      <span id="p_ci1"></span>
    </p>
  </div>
  <div id="ci2" style="z-index: 999; position: absolute; left: 160px; overflow: hidden; width: 140px; height: 140px; background-color:white;border: 1px solid red;">
    <p>id: ci2<br>
      <span id="p_ci2"></span>
    </p>
  </div>
</div>

我的代码仅适用于第一个可拖动元素。但是第二个可拖动的元素获得了第一个元素的位置。

有人可以告诉我如何在我的案件中获得每个元素的位置吗?

谢谢

1 个答案:

答案 0 :(得分:0)

问题是因为在您的代码中$(this)引用了#snaptarget,而不是您div的实例draggable()。此外elems是元素的集合,因此从中读取position()只会从第一个元素中检索值。

要解决此问题,请将您的选择器更改为$('#snaptarget div')

$('#snaptarget div').each(function() {
  var $elem = $(this);
  $elem.draggable({
    containment: '#snaptarget',
    scroll: false,
    grid: [5, 5],
    drag: function() {
      var links = Math.round($elem.position().left) / 20;
      var oben = Math.round($elem.position().top) / 20;
      $elem.find('span').html('Links: ' + links + 'mm<br>Oben: ' + oben + 'mm');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div id="snaptarget" style="background: green;height: 1720px; width: 1720px; position: absolute;margin: 20mm;">
  <div id="ci1" style="z-index: 999; position: absolute; overflow: hidden; width: 140px; height: 140px; background-color:white;border: 1px solid red;">
    <p>id: ci1<br>
      <span id="p_ci1"></span>
    </p>
  </div>
  <div id="ci2" style="z-index: 999; position: absolute; left: 160px; overflow: hidden; width: 140px; height: 140px; background-color:white;border: 1px solid red;">
    <p>id: ci2<br>
      <span id="p_ci2"></span>
    </p>
  </div>
</div>