<!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>
js div块体碰撞
最新推荐文章于 2024-07-09 11:56:29 发布