简体   繁体   中英

jQuery offset position according containment position

<script>
$(document).ready(function(e) {
    $(function(){
        $( "#draggable" ).draggable({
            containment: "#box",
            drag: function(){
                var offset = $(this).offset();
                var xPos = offset.left;
                var yPos = offset.top;

                $('#posX').val('x: ' + xPos);
                $('#posY').val('y: ' + yPos);
            }
        });
    });
});
</script>

<style>
body{margin:0;}
#draggable{width:100px; height:100px; background:red;}
#box{width:500px; height:500px; border:solid 1px #000; margin:100px;}
</style>
<div id="box">
    <div id="draggable"></div>
</div>
<input id="posX" type="text" />
<input id="posY" type="text" />

I have a div use jQuery draggable and detect the position.

My question is how can I get the offset position according to the containment $('#box') , not according to the document?

As the draggable element is appended to the body, it's not really inside the #box element at all when dragged, so you have to subtract the position of the containing element, and in your case the border as well, to get the right values

$(function(){
    var box    = $('#box').offset(),
        border = parseInt($('#box').css('border-width').replace(/\D/g,''), 10);

    $( "#draggable" ).draggable({
        containment: "#box",
        drag: function(){
            var offset = $(this).offset();
            var xPos = offset.left - box.left - border;
            var yPos = offset.top - box.top - border;

            $('#posX').val('x: ' + xPos);
            $('#posY').val('y: ' + yPos);
        }
    });
});

FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM