4

I want to get the position of an element when it is beeing dragged.

My code so far:

$(document).ready(function(){


    $("p").text($("div").position().left);
    $("p").text($("div").position().top);

    $("div").draggable();

})

This only gets the position when the page loads. I want to detect whenever the div is beeing dragged so I can write its position in the p tag.

4

2 回答 2

8
$('#dragThis').draggable(
    {
        drag: function(){
            var offset = $(this).offset();
            var xPos = offset.left;
            var yPos = offset.top;
            $('#posX').text('x: ' + xPos);
            $('#posY').text('y: ' + yPos);
        }
    });

JSFIDDLE

于 2013-08-22T16:20:12.090 回答
1

你应该看看 jQuery 官方文档的事件部分:http: //jqueryui.com/draggable/#events

drag事件将在被拖动时引发,您可以从那里获得偏移量。例如:

$(this).offset().left;
$(this).offset().top;
于 2013-08-22T16:22:41.937 回答