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

后端 未结 3 930
醉梦人生
醉梦人生 2021-02-09 01:11

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\"

相关标签:
3条回答
  • 2021-02-09 01:31

    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

    0 讨论(0)
  • 2021-02-09 01:43

    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

    0 讨论(0)
  • 2021-02-09 01:58

    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

    0 讨论(0)
提交回复
热议问题