【问题标题】:After dragging I get incorrect coordinates of all the elements but the first拖动后,我得到所有元素的不正确坐标,但第一个
【发布时间】:2015-07-23 09:27:24
【问题描述】:

我的页面上有一些 div 元素。用户可以多次拖动它们中的任何一个。每次拖动后,我都需要获取被拖动的 div 的新坐标。

我的代码与 div[0] 配合得很好:实际上每次新拖动后我都会得到新的坐标。 问题在于所有其他 div,例如 div[1]、div[2]、div[10]... 脚本在第一次拖动后获取坐标,但所有下一次的坐标仍然相同。他们不会改变。

我尝试清除变量,但没有帮助。

这个问题可能是由什么引起的?我应该检查什么才能找到解决方案?

我使用 jQuery 和 jQuery UI。代码:

$(document).ready(function(){ 
$(".rD").draggable({
stop: function(event, ui) { 
// get the index of the dragged element 
id = $(this).index();
// get coordinates of the dragged element
rect = document.getElementsByTagName("div")[id].getBoundingClientRect();
alert("top:" + rect.top + ", left: " + rect.left);
// clearing variables didn't help to solve the problem
delete rect;
delete id;
}
});

【问题讨论】:

  • 你检查过 jqueryui draggable api吗.. 它提到 ui 对象会给你原始和当前位置.. 这意味着如果需要你可以计算确切的位置..
  • 奇怪的代码风格:创建全局变量并删除它们。反正有副作用。如果有人使用全局id 变量怎么办?你清除它。
  • 也许你的$(this).index() 总是0。检查this是什么:可拖动元素还是整个容器?

标签: javascript jquery draggable


【解决方案1】:

尝试:

alert(ui.position.top, ui.position.left)

Documentation

完整代码:

$(document).ready(function(){ 
  $(".rD").draggable({
    stop: function(event, ui) { 
      // Use var keyword for your local variables
      // var rect = ui.helper[0].getBoundingClientRect();
      alert("top:" + ui.position.top + ", left: " + ui.position.left);
    }
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-05
    • 2013-01-15
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多