如何在另一个div(javascript)中保持移动div?

时间:2015-10-12 18:08:01

标签: javascript html collision-detection

我有一个非常奇怪的问题: 我在容器内部有一个移动div(也是div)。我想确保该元素保持在其中。我创建了一个controller对象,其中包含我的实用函数,实际上,我的代码适用于底部和右侧边框。但是,元素很容易通过顶部和左侧边界。

这是controller.js文件。我希望这就够了。

//A controller to store all the utility functions
var Controller = { 

    //Function that returns true if the element is outside the container
    elementIsInContainer : function(element) {
        //get the container
        var container = document.getElementById(element.parentId);

        //convert style to int
        var elementTop = parseInt(element.style.top);
        var elementLeft = parseInt(element.style.left);

        //Checks all borders, returns an object containing a bool for each side
        //a value is true, if the element is outside
        return {
            //check right border
            right: (container.offsetWidth < elementLeft + element.offsetWidth),
            //check bottom border
            bottom: (container.offsetHeight < elementTop + element.offsetHeight),
            //check left border
            left: (elementLeft < 0),
            //check top border
            top: (elementTop < 0)
        };
    },

    //Returns an object containing two strings to assign to element style
     getElementPosition : function (element) {
         var result =  { 
                    left: (parseInt(element.style.left) + "px"),
                    top: (parseInt(element.style.top) + "px")
                };
         return result;
    },

    //checks if element outside container, if so, it resets
    keepElementInContainer : function(element) {
        //Note: can it be optimized?

        //Get result of comparison with borders
        var inContainerResult = this.elementIsInContainer(element);

        //Get the coordinates of the element
        var elementPosition = this.getElementPosition(element);

        //reset top
        element.style.top = inContainerResult.top ? "0px" : elementPosition.top;
        element.debug(element.style.top);
        //reset left
        element.style.left = inContainerResult.left ? "0px" : elementPosition.left;

        //reset right
        element.style.left = inContainerResult.right ? 
                              element.maxLeft : elementPosition.left;
        //reset bottom
        element.style.top = inContainerResult.bottom ? 
                             element.maxTop : elementPosition.top;
    },       
};

0 个答案:

没有答案