檢測碰撞

<!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>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容