简体   繁体   English

jQuery偏移位置根据包含位置

[英]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. 我有一个div使用jQuery draggable并检测位置。

My question is how can I get the offset position according to the containment $('#box') , not according to the document? 我的问题是如何根据包含$('#box')获取偏移位置,而不是根据文档?

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 由于可拖动元素附加到正文,因此在拖动时它根本不在#box元素内部,因此您必须减去包含元素的位置,并且在您的情况下也必须减去边框,以获得正确的值

$(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 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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