How do I get position x and y from jQuery ui draggable?

前端 未结 4 2231
灰色年华
灰色年华 2020-12-30 17:04

Here an example http://jsfiddle.net/naqbq/

How do I grab current position for x and y after re-position the image?



        
相关标签:
4条回答
  • 2020-12-30 17:19

    You can use jQuery's .offset().

    http://api.jquery.com/offset/

    alert($('#image').offset().top);
    alert($('#image').offset().left);
    
    0 讨论(0)
  • 2020-12-30 17:24

    In the stop callback, you can use ui.helper to access the dragged element. Then use offset on it, as Brad suggested:

    $("#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());
        }
    });​
    

    Then, it's just a matter of adjusting it to your wrapper - subtracting its offset and its border's width - and setting it to your input's val. (sorry for hardcoding the border, but I couldn't extract it using css) (Edit: there it is! found the solution in another question)

    http://jsfiddle.net/mgibsonbr/naqbq/4/

    0 讨论(0)
  • 2020-12-30 17:25

    You should use the built in stop event:

    $("#image").draggable({
        stop: function() { 
            // check for positioning here using .css or .offset
        }
    });
    
    0 讨论(0)
  • 2020-12-30 17:32

    You can obtain the top, and lef:

    $('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. 
      }
    })
    
    0 讨论(0)
提交回复
热议问题