一,通过计算两个盒子的四条边来判断盒子是否碰撞,
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <base href="<%=basePath%>"> <style type="text/css"> *{ margin: 0px; padding: 0px; } .box{ width: 146px; height: 100px; border: 1px solid darkgreen; border-radius: 22px 16px; background-color: darkkhaki; } </style> <script type="text/javascript" src="js/opDom.js"></script> <script type="text/javascript"> function $(oId){ return document.getElementById(oId); }
//定义静态变量(不可修改) const LEFT=37,TOP=38,RIGHT=39,BOTTOM=40; var lleft=0; var ltop=0; var T2=0; var L2=0; var R2=0; var B2=0; var ddiv=0; window.onload = function(){ ddiv=$("dong"); var bdiv=$("bddiv"); //获取id为bddiv的盒子的四条边的位置 T2=bdiv.offsetTop; L2=bdiv.offsetLeft; R2=bdiv.offsetLeft+bdiv.offsetWidth; B2=bdiv.offsetTop+bdiv.offsetHeight; document.onkeydown = function(){ var event=window.event||event; //获取按下的键盘按键Unicode值 var code=event.keyCode; //判断被按下的按键 if(code==LEFT){ lleft=lleft-1; execute(lleft,ltop); pd(); return; } if(code==TOP){ ltop=ltop-1; execute(lleft,ltop); pd(); return; } if(code==RIGHT){ lleft=lleft+1; execute(lleft,ltop); pd(); return; } if(code==BOTTOM){ ltop=ltop+1; execute(lleft,ltop); pd(); return; } } } //为盒子添加位置属性 function execute(left,top){ setTimeout(function(){ ddiv.style.left=left+"em"; ddiv.style.top=top+"em"; },100) } //判断盒子是否碰撞 function pd(){ //0,0,148,102,213,717,865,315 site(function(T1,L1,R1,B1){ if((B2>B1&&B1>T2&&R2>R1&&R1>L2)||(L2<L1&&L1<R2&&B2>B1&&B1>T2)||(T2<T1&&T1<B2&&L2<L1&&L1<R2)||(T2<T1&&T1<B2&&R2>R1&&R1>L2)){ alert("盒子碰撞") } }) } //获取id为ddiv的盒子的四边位置 function site(fun){ var T=ddiv.offsetTop; var L=ddiv.offsetLeft; var R=ddiv.offsetLeft+ddiv.offsetWidth; var B=ddiv.offsetTop+ddiv.offsetHeight; fun(T,L,R,B); } </script> </head> <body> //动的盒子 <div class="box" id="dong" style="position: absolute;left: 0px;top: 0px;"> </div> <div style="height: 500px;width: 1000px"> //不动的盒子 <div class="box" id="bddiv"style="float: right; border-radius:0px;background-color: darkgreen; position: absolute;left: 717px;top: 213px;}"> </div> </div> </body> </html>