简体   繁体   English

获取可拖动对象相对于div的位置

[英]Get position of dragable object, relative to a div

Here is the jsFiddle , where I have a football field, where the user shall partition 10 players, in two five-membered teams. 这是jsFiddle ,这里有一个足球场,用户应在10个球员中分成两个五人小组。 I want to know whether he dragged a player on the left or night side (assuming the center line of the field is border). 我想知道他是在左侧还是在夜间拖动玩家(假设该区域的中心线是边框)。

Here the js code: 这里的js代码:

$(".dragNdrop").draggable({
  drag: function(){
    var offset = $(this).offset();
    var xPos = offset.left;
    var yPos = offset.top;
      console.log('x: ' + xPos);
      console.log($('#footballField').width());
    }
});

I've also tried with position() and offset() , but I can't seem to find the right formula to do it. 我也尝试过position()offset() ,但是我似乎找不到合适的公式来做到这一点。

So, how will I find whether the players is positioned in the left or the right side of the div ? 那么,我将如何发现玩家是位于div的左侧还是右侧?

Related question: How to get the position of a draggable object 相关问题: 如何获取可拖动对象的位置

If $('#footballField').width() is the width of the field, you can check if the xPos of the dragNdrop element is less or higher than the footballField left + his width divided by 2: 如果$('#footballField')。width()是字段的宽度,则可以检查dragNdrop元素的xPos小于还是大于footballField left +他的宽度除以2:

$(".dragNdrop").draggable({
    drag: function(){
        var offset = $(this).offset();
        var xPos = offset.left;
        var yPos = offset.top;
        console.log('x: ' + xPos);
        //console.log('y: ' + yPos);
        console.log('offset: ' + $('#footballField').offset().left);
        var fieldLeft = $('#footballField').offset().left;
        console.log($('#footballField').width());
        if(xPos < fieldLeft + $('#footballField').width()/2){
             console.log('I am at left');
        }else{
            console.log('I am at right');
        }

    }
});

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

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