简体   繁体   中英

Collision detection with JavaScript. (Check if 2 Block Level elements are touching)

I Want To check if my div have touch another div

here is my Work

$(document).mousemove(function(event){
        if(getmouse){
            var newX= event.pageX-20;
            var newY= event.pageY-20;
            $('.mybox').css('left',newX + "px");
            $('.mybox').css('top',newY+ "px");
            var checkY = parseInt($('.box1').css('top').slice(0,-2));
            var checkX = parseInt($('.box1').css('left').slice(0,-2));
            var padingval = parseInt($('.box').css('padding').slice(0,-2))*2;
            console.log(checkY+padingval+" - "+newY);
            if((newY==checkY&&newX==checkX)||newY+20<checkY-padingval
               ||newY-20<checkY+padingval)
            {
                alert('Game Over');
                getmouse = false;
                $('.mybox').css('top',"240px");
                $('.mybox').css('left',"420px");
            }
        }
    })

http://jsfiddle.net/48m6rof6

if My div Touch any div it Must alert Game over and return to its place I have checked if it touched first box but if there is any simple way to check ?

您可以像这样使用Jquery冲突插件

var x = $("#div1").collision(".div2");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM