多个jQuery UI元素的X和Y位置

我试图使用jQuery UI收集多个可拖动元素的位置。

目前我可以获得一个元素的位置,但是当我移动另一个元素时,两个位置都会改变。

请有人协助我获取多个可拖动物品的单独位置。

http://codepen.io/anon/pen/nLGIl

HTML

Test 1

This is a test

Test 2

This is a test

CSS

 .dragThis { min-width: 50px; max-width: 300px; min-height: 50px; max-height: 400px; overflow: auto; padding: 10px; background: #efefef; border: 3px solid #ccc; border-radius: 10px; display: inline-block; position: absolute; top: 0px; left: 0px; z-index: 0; } .dragThis h2 { font-size: 20px; margin: 0; padding: 0; } .dragThis ul { list-style: none; margin: 0; padding: 0; } .top {z-index: 2; position: relative} .bottom {z-index: 1; position: relative} 

JS

 $(document).ready(function() { var a = 3; $('.dragThis').draggable( { start: function(){ $(this).css("z-index", a++); }, drag: function(){ var offset = $(this).offset(); var xPos = offset.left; var yPos = offset.top; $('.posX').text('x: ' + xPos); $('.posY').text('y: ' + yPos); } }); $('.dragThis').click(function(){ $(this).addClass('top').removeClass('bottom'); $(this).siblings().removeClass('top').addClass('bottom'); $(this).css("z-index", a++); }); }); 

首先,Double ID不好.. box-1和box-2更好:

您正在使用类’.posX’等匹配所有元素。试试这个:

 $(document).ready(function() { var a = 3; $('.dragThis').draggable( { start: function(){ $(this).css("z-index", a++); }, drag: function(){ var offset = $(this).offset(); var xPos = offset.left; var yPos = offset.top; $(this).find('.posX').text('x: ' + xPos); $(this).find('.posY').text('y: ' + yPos); } }); $('.dragThis').click(function(){ $(this).addClass('top').removeClass('bottom'); $(this).siblings().removeClass('top').addClass('bottom'); $(this).css("z-index", a++); }); }); 
 $('.posX', this).text('x: ' + xPos); $('.posY', this).text('y: ' + yPos); 

代替

 $('.posX').text('x: ' + xPos); $('.posY').text('y: ' + yPos); 

示例 – http://codepen.io/anon/pen/yKvcB

通过执行此$('.posX') ,当您只需要活动框上的那些时,您已选择此类的所有元素,因此代码将如下所示:

 $(this).find('.posX').text('x: ' + xPos); $(this).find('.posY').text('y: ' + yPos); 

演示: http : //codepen.io/anon/pen/FpCtu