jQuery-UI Draggable:打印出相对于DIV容器的坐标

Tha*_*ham 6 jquery jquery-ui

演示展示了在使用jQuery拖动组件时如何发送事件.我有一个组件DIV,当我拖动该组件时,我想打印出对于DIV容器的组件坐标,任何jQuery pro都可以帮助我.这是我到目前为止所得到的.

<div id="container" style="width: 400px; height: 4000px; border: 1px solid black;" >
    <div id="draggable" style="width: 150px; height: 150px; background-color: black; cursor: move;">
        <div class="count"/>               
    </div>
</div>  
<script>            
    jQuery(function(){                                
        jQuery("#draggable").draggable({
            containment: "#contain",
            scroll: false,
            drag: function(){

            }
        });
        function updateCoordinate(newCoordinate){
            jQuery(".count").text(newCoordinate);
        }
    });
</script>
Run Code Online (Sandbox Code Playgroud)

在拖动的回调事件中,我需要弄清楚pageX, pageY以及offsetX, offsetY在拖动时找出组件的相对位置.我是jQuery的新手.我知道我可以获得两者pageX, pageY并且offsetX, offsetY喜欢这样

jQuery("#container").click(function(event){
    var offset = jQuery(this).offset();
    var pageX = event.pageX;
    var pageY = event.pageY;
});
Run Code Online (Sandbox Code Playgroud)

但我不确定如何将它们组合在一起.

Jam*_*gne 14

像这样?

http://jsfiddle.net/aasFx/36/

$(function() {
    $("#draggable").draggable({
        containment: "#contain",
        scroll: false,
        drag: function() {
            var $this = $(this);
            var thisPos = $this.position();
            var parentPos = $this.parent().position();

            var x = thisPos.left - parentPos.left;
            var y = thisPos.top - parentPos.top;

            $this.text(x + ", " + y);
        }
    });
});?
Run Code Online (Sandbox Code Playgroud)


dro*_*owe 8

你可能想要做的是将父容器CSS设置为'position:relative',将'draggable item'设置为'position:absolute'.然后,使用$(this).position().left/top之类的东西将相对于父容器.

见这里:http://jsfiddle.net/bTULc/1/