如何限制拖动元素在interact.js中重叠

时间:2016-05-31 11:57:43

标签: overlapping

容器中的拖动元素不应该重叠我们如何限制。 请帮忙

interact API link

1 个答案:

答案 0 :(得分:0)

很抱歉,这个问题没有得到解决。我相信你必须手动检查元素的顶部,底部,左边和右边的位置,所以这就是我所做的:

//Call this function from within your .on('dragmove') method.
//It should replace your translations.

function noOverlap(event, overlapElements){

    //just for flagging when the target would overlap another element
    var overlap = false;
    var targetDims = event.target.getBoundingClientRect();

    for(i = 0; i < overlapElements.length; i++){
        var overlapElementDims =  
        overlapElements[i].getBoundingClientRect();

        //make sure the element doesn't look at itself..
        if(overlapElements[i] != event.target){
            //checks if the target "doesn't" overlap
            if(((targetDims.right + dx) < (overlapElementDims.left + 1)) 
            ||((targetDims.left + 1 + dx) > (overlapElementDims.right)) 
            ||((targetDims.top + 1 + dy) > (overlapElementDims.bottom)) 
            ||((targetDims.bottom + dy) < (overlapElementDims.top + 1))}{

            //Basically, the target element doesn't overlap the current 
            //element in the HTMLCollection, do nothing and go to the 
            //next iterate
            }
            else{
                //This is if the target element would overlap the current element

                //set overlap to true and break out of the for loop to conserve time.

                overlap = true;
                break;
            }
        }
    };

    if(overlap === false){

        //if there's no overlap, do your normal stuff, like:
        event.target.x += dx;
        event.target.y += dy;

        event.target.style.webkitTransform =
            event.target.style.transform =
                'translate(' + event.target.x + 'px, ' + event.target.y + 'px)';

        //then reset dx and dy
        dy = 0;
        dx = 0;
    }
    else{
        if(event.interaction.pointers[event.interaction.pointers.length - 1].type 
        === "pointerup"){

            //check if the target "is" in the restriction zone
            var restriction = 
            interact(event.target).options.drag.restrict.restriction;
            var restrictionDims = restriction.getBoundingClientRect();

            if((targetDims.right > restrictionDims.right) || 
            (targetDims.left < restrictionDims.left) || 
            (targetDims.bottom > restrictionDims.bottom) || 
            (targetDims.top < restrictionDims.top)){
                event.target.style.webkitTransform =
                event.target.style.transform =
                    'translate(0px, 0px)';

                //then reset dx and dy
                dy = 0;
                dx = 0;

                //then reset x and y
                event.target.x = 0;
                event.target.y = 0;
            }
        }       
    } 
}