练习-元素拖拽过程中的碰撞检测

效果:
在这里插入图片描述
代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
    body{
        margin: 0;
    }
    #div1{
        width: 200px;
        height: 200px;
        background-color: red;
        position: absolute;
        left: 50%;
        top: 50%;
        /* transform: translate(-50%,-50%); */   /*这种写法只是视觉上的位置发生变化了,实际位置并没有发生变化*/
        margin-left:-100px;
        margin-top: -100px;
    }
    #div2{
        width: 150px;
        height: 150px;
        background-color: blue;
        position: absolute;
        left: 0;
        top: 0;
    }
    </style>
</head>
<body>
    <!-- 解决办法:给不动的元素div1四个边分别做延长线,就会出现上下左右边界线,不进入这些边界线就不会碰撞 -->
    <div id="div1"></div>
    <div id="div2"></div>
    <script>
    var oDiv1 = document.getElementById("div1");
    var oDiv2 = document.getElementById("div2");
    oDiv2.onmousedown = function (){
        var disX = event.pageX - oDiv2.offsetLeft;
        var disY = event.pageY - oDiv2.offsetTop;
        document.onmousemove = function (){
            var nLeft = event.pageX - disX;
            var nTop = event.pageY - disY;
            oDiv2.style.left = nLeft + "px";
            oDiv2.style.top = nTop + "px";
            if(oDiv2.offsetLeft+oDiv2.offsetWidth<oDiv1.offsetLeft||oDiv2.offsetLeft>oDiv1.offsetLeft+oDiv1.offsetWidth||oDiv2.offsetTop+oDiv2.offsetHeight<oDiv1.offsetTop||oDiv2.offsetTop>oDiv1.offsetTop+oDiv1.offsetHeight){
                oDiv1.style.backgroundColor = "red";
            }else{
                oDiv1.style.backgroundColor = "yellow";
            }
        }
        document.onmouseup = function (){
            document.onmouseup = document.onmousemove = null;
        }
        return false;
    }
    </script>
</body>
</html>
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页