拖动后,除了第一个元素以外,我得到了所有元素的不正确坐标



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

我的代码与Div [0]的效果很好:在每个新拖动后,我实际上都会得到新的坐标。问题在于所有其他Divs,例如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;
}
});

尝试:

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

文档

整个代码:

$(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);
    }
  });
});

最新更新