开发者

jQuery-UI Draggable: Print out the coordinate relative to a DIV container

This demo shows how send event when dragging the component around using jQuery. I have a component inside a DIV, and when I drag that component I want to print out the coordinate of the component relative to the DIV container, can any jQuery pro help me out here. Here is what I got so far.

<div id="container" style="width: 400px; height: 4000px; border: 1px solid black;" >
    <div id="draggable" style="width: 150px; height: 150px; background-color开发者_Python百科: 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>

In the callback event for drag, I need to figure out the pageX, pageY as well as the offsetX, offsetY to find out the relative position of the component when i drag. I am very new to jQuery. I know that I can obtain the both pageX, pageY and offsetX, offsetY like this

jQuery("#container").click(function(event){
    var offset = jQuery(this).offset();
    var pageX = event.pageX;
    var pageY = event.pageY;
});

but I am not sure how to combine them together.


Like this?

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);
        }
    });
});​


What you might want to do is set the parent container CSS to 'position: relative', and the 'draggable item' to 'position: absolute'. Then, using things like $(this).position().left / top will be relative to the parent container.

See here: http://jsfiddle.net/bTULc/1/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜