如何从jQuery UI的可拖动元素中获取x和y位置?

4

这里有一个例子:http://jsfiddle.net/naqbq/

当重新定位图片后,如何获取当前位置的xy

<input type="hidden" name="source_x" id="source_x" />
<input type="hidden" name="source_y" id="source_y" />
4个回答

10
stop回调函数中,你可以使用ui.helper来访问拖动的元素。然后像Brad建议的那样,在它上面使用offset

stop回调函数中,可以使用ui.helper来访问被拖动的元素,然后可以按照Brad的建议,在该元素上使用offset

$("#image").draggable({
    stop:function(event,ui) {
        var wrapper = $("#wrapper").offset();
        var borderLeft = parseInt($("#wrapper").css("border-left-width"),10);
        var borderTop = parseInt($("#wrapper").css("border-top-width"),10);
        var pos = ui.helper.offset();
        $("#source_x").val(pos.left - wrapper.left - borderLeft);
        $("#source_y").val(pos.top - wrapper.top - borderTop);
        alert($("#source_x").val() + "," + $("#source_y").val());
    }
});​
然后,只需要根据您的包装器进行调整-减去其偏移量和边框宽度-并将其设置为您的输入的val。(编辑:在另一个问题中找到了解决方法)(抱歉硬编码边框,但我无法使用css提取它)。 http://jsfiddle.net/mgibsonbr/naqbq/4/

5

2
您应该使用内置的停止事件:
$("#image").draggable({
    stop: function() { 
        // check for positioning here using .css or .offset
    }
});

2

您可以获取顶部和左侧:

$('selector').draggable({
  drag: function(event, ui) {
    ui.position.top; // .left
    // or
    $('selector').position().top; // current position of an element relative to the offset parent
    $('selector').offset(); // retrieves the current position relative to the document. 
  }
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接