开发者

jQuery - get relative position and attribute of dropped elements

I have draggable elements which can be dropped in droppable areas. If an element is dropped, the drop function is called:

$('#droppable').droppable({
    scope: "items",
    drop: function (event, ui) {
        // this one is called if an element is dropped in this droppable area
    }
});

My draggable el开发者_JAVA百科ement:

<div class="drag" data-noteid="10">Drag me</div>
...
$('.drag').draggable({
    revert: "invalid",
    scope: "items"
});

What I need to know if the element is dropped is the value of data-noteid and the relative position of the droppable area. So, if the element is dropped on the upper left corner, the x/y coordinates must be 0/0.

I created a full working example here: http://jsbin.com/utivo5/2/

So normally I can access the attributes like this:

alert($(this).data("noteid"));

alert($(this).position().top);
alert($(this).position().left);

but all I get in this case is undefined.

Do anyone know how I can access them? I think it must be possible with event or ui which is a parameter of the called drop function?!

Thank you in advance & Best Regards, Tim.


In this case you want the ui argument to get the draggable, rather than this which refers to the droppable area, specifically ui.draggable here. It should look like this overall:

drop: function (event, ui) {
  var pos = ui.draggable.offset(), dPos = $(this).offset();
  alert("nodeid: " + ui.draggable.data("noteid") + 
        ", Top: " + (pos.top - dPos.top) + 
        ", Left: " + (pos.left - dPos.left));
}

For the position, we need to subtract the droppable's top/left position to get the value you want here, that's the dPos above getting removed.

You can test your demo with the above changes working here.


I found for my circumstances that the above didn't work. Not sure why - it always gave me an X = -7 and Y = 229.

But this did work (located in drop function handler):

alert('X pos in drop parent container = ' + (ui.position.top - $(this).offset().top));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜