2017-03-23 39 views
1

我試圖使用jQuery UI獲取多個可拖動元素的位置。我發現了一個類似的問題(X and Y Positions of multiple jQuery UI Elements),但在我的情況下,有一個div擁有多個可拖動的div,所以答案不適用於我。jquery顯示拖動後多個元素的位置

$('#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>

我的代碼僅適用於第一拖動元素。但第二個可拖動元素獲取第一個元素的位置。

請有人能告訴我如何獲得每個元素在我的情況下的位置?

謝謝

回答

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>

+0

非常感謝您! – rince