How to detect when an element over another element in JavaScript?

安稳与你 提交于 2019-12-21 12:31:55

问题


I wrote most of the code... And when the element is "fully" over the other element it works. The problem is that I don't just want it to be true when the element is "fully" over the element, I also want it to be true when the element is partly over the other element.

Here is my code:

    element = this.element.getStyles('left', 'top', 'width', 'height');
    elementLeftX = element.left.toInt();
    elementLeftY = element.top.toInt();
    elementRightX = (element.width.toInt() + element.left.toInt());
    elementRightY = (element.top.toInt() + element.height.toInt());

    el = this.positions ? this.positions[i] : this.getDroppableCoordinates(el); // Element drop area
    elLeftX = el.left.toInt();
    elLeftY = el.top.toInt();
    elRightX = (el.width.toInt() + el.left.toInt());
    elRightY = (el.height.toInt() + el.top.toInt());

   if (((elLeftY <= elementLeftY) && (elementLeftY <= elRightY)) && ((elLeftY <= elementRightY) && (elementRightY <= elRightY))) {
        if (((elLeftX <= elementLeftX) && (elementLeftX <= elRightX)) && ((elLeftX <= elementRightX) && (elementRightX <= elRightX))) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }

I am very confused and I have been playing around for a while and I just can't get it to work.


回答1:


Standard video game method:

doElsCollide = function(el1, el2) {
    el1.offsetBottom = el1.offsetTop + el1.offsetHeight;
    el1.offsetRight = el1.offsetLeft + el1.offsetWidth;
    el2.offsetBottom = el2.offsetTop + el2.offsetHeight;
    el2.offsetRight = el2.offsetLeft + el2.offsetWidth;

    return !((el1.offsetBottom < el2.offsetTop) ||
             (el1.offsetTop > el2.offsetBottom) ||
             (el1.offsetRight < el2.offsetLeft) ||
             (el1.offsetLeft > el2.offsetRight))
};

See demo




回答2:


If you are interested in using jQuery (or if you already are) there are some great collision detection plugins available. Here is a previous answer detailing one https://stackoverflow.com/a/6052254/374866




回答3:


When you are attempting is called "collision detection". You need to get the element's COMPUTED offsets and dimensions, not just the element's style declarations.

This posting may help explain:

jQuery/JavaScript collision detection



来源:https://stackoverflow.com/questions/9607252/how-to-detect-when-an-element-over-another-element-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!