jQuery/JavaScript collision detection

前端 未结 7 2145
情话喂你
情话喂你 2020-11-22 04:49

How to detect if two

elements have collided?

The two divs are simple coloured boxes travelling perpendicular to each other, so no complicate

7条回答
  •  有刺的猬
    2020-11-22 05:15

    Post is old, May be it help someone...

    function CheckDiv()
    {
    var ediv1 = document.getElementById('DIV1');
    var ediv2 = document.getElementById('DIV2');
    
     ediv1.top = $(ediv1).offset().top;
     ediv1.left = $(ediv1).offset().left;
     ediv1.right = Number($(ediv1).offset().left) + Number($(ediv1).width());
     ediv1.bottom = Number($(ediv1).offset().top) + Number($(ediv1).height());
    
     ediv2.top = $(ediv2).offset().top;
     ediv2.left = $(ediv2).offset().left;
     ediv2.right = Number($(ediv2).offset().left) + Number($(ediv2).width());
     ediv2.bottom = Number($(ediv2).offset().top) + Number($(ediv2).height());
    
    if (ediv1.right > ediv2.left && ediv1.left < ediv2.right && ediv1.top < ediv2.bottom && ediv1.bottom > ediv2.top)
     {
    alert("hi");
    }
    
    if (ediv1.left > ediv2.left && ediv1.top > ediv2.top && ediv1.right < ediv2.right && ediv1.bottom < ediv2.bottom)
     {
    alert("hello");
        }
    }
    

提交回复
热议问题