How to get relative position of a draggable item when dropped?
I have the following:
$(function() {
// Make images draggable.
$(".item").draggable({
// Find position where image is dropped.
stop: function(event, ui) {
// Show dropped position.
var Stoppos = $(this).position();
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
}
});
});
This will get the position of the item when I drop it, but it is relative to the browser window, not the d开发者_开发知识库iv they are within. How can I get their relative position?
edit-> Here is the html/css:
<style type="text/css">
.container {
margin-top: 50px;
cursor:move;
}
#screen {
overflow:hidden;
width:500px;
height:500px;
clear:both;
border:1px solid black;
}
</style>
<body>
<div class="container">
<div id="screen">
<img id="productid_1" src="images/KeypadLinc OFF.jpg" class="item" alt="" title="" />
<img id="productid_2" src="images/KeypadLinc ON.jpg" class="item" alt="" title="" />
</div>
</div>
<div id="stop">Waiting image getting dropped...</div>
</body>
Give the parent div position: relative
.
#screen {
position: relative;
...
}
Set the containment attribute. For example:
$(".item").draggable( { containment: 'parent' } );
Keep in mind that the containment element (in this case parent
) may not work with certain selectors.
From the documentation:
Constrains dragging to within the bounds of the specified element or region. Possible string values: 'parent', 'document', 'window', [x1, y1, x2, y2].
See the jQuery UI Documentation for more information.
精彩评论