检测碰撞

2017-04-18  本文已影响0人  洛洛kkkkkk
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style type="text/css">
            .redDiv{
                width: 400px;
                height: 400px;
                background-color: greenyellow;
                position: relative;
                margin: 100px auto;
            }
            .yellow{
                width: 50px;
                height: 50px;
                background-color: yellow;
                position: absolute;
            }
        </style>
    </head>
    <body>
        <div class="redDiv"></div>
        <div class="yellow"></div>
    </body>
    <script type="text/javascript">
        var redDiv=document.querySelector(".redDiv");
        var yellow= document.querySelector(".yellow");
        yellow.onmousedown = function (ev) {
            var x=ev.offsetX;
            var y=ev.offsetY;
            document.onmousemove = function (e) {
            yellow.style.left=e.clientX-x+'px';
            yellow.style.top=e.clientY-y+'px';
//          碰撞检测
//          1.蓝右>红左
//          2.蓝顶<红底
//          3.蓝底>红顶
//          4.蓝左<红右
            if(yellow.offsetLeft+yellow.offsetWidth>=redDiv.offsetLeft && yellow.offsetTop<=redDiv.offsetTop+redDiv.offsetHeight && yellow.offsetTop+yellow.offsetHeight>=redDiv.offsetTop && yellow.offsetLeft<=redDiv.offsetLeft+redDiv.offsetWidth){
                console.log("碰到我了");
            }
        }
        }
        yellow.onmouseup = function () {
            document.onmousemove= function () {
                
            }
        }
    
    
        
    </script>
</html>
上一篇 下一篇

猜你喜欢

热点阅读