2013-06-25 28 views
1

即時嘗試使用jQuery UI來收集多個可拖動元素的位置。多個jQuery UI元素的X和Y位置

目前我可以得到一個元素的位置,但是當我移動另一個元素時,兩個位置都會改變。

請有人幫助我獲得多個可拖動項目的單獨位置。

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

HTML

<div class="dragThis" id="box-1"style="top: 100px; left: 50px;" > 
    <h2>Test 1</h2> 
    <p>This is a test</p> 
    <ul> 
    <li class="posX"></li> 
    <li class="posY"></li> 
    </ul> 
</div> 

<div class="dragThis" id="box-1" style="top: 50px; left: 100px;" > 
    <h2>Test 2</h2> 
    <p>This is a test</p> 
    <ul> 
    <li class="posX"></li> 
    <li class="posY"></li> 
    </ul> 
</div> 

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++); 
    }); 

}); 

回答

1

首先,雙號的都不好..箱1和箱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++); 
    }); 

}); 
0

通過這樣做$('.posX')您選擇這個類的所有元素時,你只需要那些在活動中,這樣的代碼將是這樣的:

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

DEMO:http://codepen.io/anon/pen/FpCtu

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

,而不是

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

樣本 - http://codepen.io/anon/pen/yKvcB