js div块体碰撞

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div
        {
            width: 50px;
            height: 50px;
            position: absolute;

        }
        #div0
        {
            background-color: dodgerblue;
            left: 50px;
            top: 50px;
            transition: all 1s;
        }
        #div1
        {
            background-color: rebeccapurple;
            left: 250px;
            top: 250px;
        }
    </style>
</head>
<body>
    <div id="div0"></div>
    <div id="div1"></div>
<script>
    var div1=document.querySelector("#div1");
    var div0=document.querySelector("#div0");
    div1.addEventListener("mousedown",mouseHandler);

    function mouseHandler(e) {
        switch (e.type){
            case "mousedown":
                this.addEventListener("mouseup",mouseHandler);
                this.point={x:e.offsetX,y:e.offsetY};
                window.divs=this;
                window.addEventListener("mousemove",mouseHandler);
                break;
            case "mouseup":
                this.removeEventListener("mouseup",mouseHandler);
                window.removeEventListener("mousemove",mouseHandler);
                break;
            case "mousemove":
                var point={x:e.x-this.divs.point.x,y:e.y-this.divs.point.y};
                this.divs.style.left=point.x+"px";
                this.divs.style.top=point.y+"px";
                hitTest();
                break;
        }
    }
    function hitTest() {
        var bool=false;
        var pointArr=[
            {x:div1.offsetLeft,y:div1.offsetTop},
            {x:div1.offsetLeft+div1.offsetWidth,y:div1 .offsetTop},
            {x:div1.offsetLeft,y:div1.offsetTop+div1.offsetHeight},
            {x:div1.offsetLeft+div1.offsetWidth,y:div1.offsetTop+div1.offsetHeight}
        ];
        for(var i=0;i<pointArr.length;i++){
            if(pointArr[i].x>div0.offsetLeft && pointArr[i].x<div0.offsetLeft+div0.offsetWidth && pointArr[i].y>div0.offsetTop && pointArr[i].y<div0.offsetTop+div0.offsetHeight){
                bool=true;
                break;
            }
        }
        if(bool){
            div0.style.left=Math.floor(Math.random()*(document.documentElement.clientWidth-div0.offsetWidth))+"px";
            div0.style.top=Math.floor(Math.random()*(document.documentElement.clientHeight-div0.offsetHeight))+"px";
        }
    }
</script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值