我们利用元素获取矩形对象来实现
dom.getBoundingClientReact();
left 元素左边距离页面左边的距离
right 元素右边距离页面左边的距离
top 元素顶边距离页面顶端的距离
bottom 元素下边距离页面顶端的距离
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ 50px; height:50px; background-color: red; position: absolute; } #div0{ background-color: blue; } </style> </head> <body> <div id="div0"></div> <div id="div1"></div> <script> var obj={ divRandom:function(elem){ //文档减去元素的宽高 var w=document.documentElement.clientWidth-elem.clientWidth; var h=document.documentElement.clientHeight-elem.clientHeight; //随机位置 elem.style.left=Math.random()*w+"px"; elem.style.top=Math.random()*h+"px"; }, tuozhuai:function (elem){ elem.addEventListener("mousedown",mouseHandler); function mouseHandler(e){ switch(e.type){ case "mousedown": e.preventDefault(); document.addEventListener("mousemove",mouseHandler); this.addEventListener("mouseup",mouseHandler); this.x=e.offsetX; this.y=e.offsetY; document.elem=this; break; case "mousemove": document.elem.style.left=e.clientX-document.elem.x+"px"; document.elem.style.top=e.clientY-document.elem.y+"px"; //移动碰撞事件,这里需要自定义事件抛发,要不不触发 var evn=new Event("hit"); this.elem.dispatchEvent(evn); break; case "mouseup": document.removeEventListener("mousemove",mouseHandler); break; } } }, hit:function(elem1,elem2){ var rand0=elem1.getBoundingClientRect(); var rand1=elem2.getBoundingClientRect(); //如果元素1的左上角 碰到元素2 if(rand0.left>=rand1.left && rand0.left<=rand1.right && rand0.top>=rand1.top && rand0.top <=rand1.bottom){ return true; } //右上 if(rand0.right>=rand1.left && rand0.left<=rand1.left && rand0.top>=rand1.top && rand0.top <=rand1.bottom){ return true; } return false; } } var div0=document.querySelector("#div1"); var div=document.querySelector("#div0"); obj.divRandom(div); obj.tuozhuai(div0); //添加div0的自定义事件,碰撞后触发 div0.addEventListener("hit",hitHandler); function hitHandler(e){ if(obj.hit(div0,div)){ obj.divRandom(div); } } </script> </body> </html>