繁体   English   中英

jQuery-获取放置元素的相对位置和属性

[英]jQuery - get relative position and attribute of dropped elements

我有可拖动的元素,可以将其拖放到可拖放区域中。 如果drop了元素,则drop函数将被调用:

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

我的可拖动元素:

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

我需要知道是否删除了元素是data-noteid的值和data-noteid区域的相对位置。 因此,如果将元素放在左上角,则x / y坐标必须为0/0。

我在这里创建了一个完整的工作示例: http : //jsbin.com/utivo5/2/

所以通常我可以这样访问属性:

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

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

但是我在这种情况下得到的都是undefined

有谁知道我该如何访问他们? 我认为eventui必须是可能的,这是调用drop函数的参数吗?

蒂姆,在此先感谢您和最诚挚的问候。

在这种情况下你想要的ui参数,以获得可拖动,而不是this是指可投放区域,具体ui.draggable这里。 整体看起来应该像这样:

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

对于该位置,我们需要减去可放置对象的顶部/左侧位置,以在此处获得所需的值,即上方的dPos被移除。

您可以在此处使用上述更改测试您的演示

我发现我的情况上述无效。 不知道为什么-它总是给我X = -7和Y = 229。

但这确实有效(位于放置函数处理程序中):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM