【问题标题】:jQuery - get relative position and attribute of dropped elementsjQuery - 获取被删除元素的相对位置和属性
【发布时间】:2011-01-03 11:18:41
【问题描述】:

我有可以拖放到可拖放区域的可拖动元素。如果删除了一个元素,则调用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的值和可丢弃区域的相对位置。所以,如果元素被放在左上角,x/y坐标必须是0/0。

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

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

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

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

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

有人知道我如何访问它们吗?我认为event 或ui 一定是可能的,这是被调用的drop 函数的参数?!

提前感谢您和最诚挚的问候,蒂姆。

【问题讨论】:

    标签: javascript jquery jquery-ui jquery-ui-draggable


    【解决方案1】:

    在这种情况下,您希望 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));
    }
    

    对于位置,我们需要减去droppable的顶部/左侧位置以获得您想要的值,即上面的dPos被删除。

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

    【讨论】:

      【解决方案2】:

      根据我的情况,我发现上述方法不起作用。不知道为什么 - 它总是给我一个 X = -7 和 Y = 229。

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

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

      【讨论】:

      • 对我也没有用,但其他答案只适用于有“简单”要求的人:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-03
      相关资源
      最近更新 更多