碰撞检测
HTML
<div id="box"></div> <img src="img/2.jpg"/>
CSS
#box,img{ width: 100px; height: 100px; background: red; position: absolute; } #box{ left: 300px; top: 200px; }
JS
var Box=document.getElementById("box"); var oImg=document.getElementsByTagName("img")[0]; oImg.onmousedown=function(ev){ var ev=ev||event; var disX=ev.clientX-this.offsetLeft; var disY=ev.clientY-this.offsetTop; //设置全局捕获 //所有的onmousemove或者onmouseup都被oImg截获,然后作用在oImg身上 if(oImg.setCapture){ oImg.setCapture(); } document.onmousemove=function(ev){ var ev=ev||event; var L=ev.clientX-disX; var T=ev.clientY-disY; //限制拖拽范围 //横向 if(L<0){ L=0; }else if(L>document.documentElement.clientWidth-oImg.offsetWidth){ L=document.documentElement.clientWidth-oImg.offsetWidth; } //纵向 if(T<0){ T=0; }else if(T>document.documentElement.clientHeight-oImg.offsetHeight){ T=document.documentElement.clientHeight-oImg.offsetHeight; } //碰撞检测 var L1=oImg.offsetLeft; var B1=oImg.offsetLeft+oImg.clientWidth; var T1=oImg.offsetTop; var B2=oImg.offsetTop+oImg.clientHeight; var L2=Box.offsetLeft; var B3=Box.offsetLeft+Box.clientWidth; var T2=Box.offsetTop; var B4=Box.offsetTop+Box.clientHeight; if(B1<L2||B3<L1||B2<T2||B4<T1){ Box.style.background="red"; }else{ Box.style.background="green"; } oImg.style.left=L+'px'; oImg.style.top=T+'px'; } document.onmouseup=function(){ document.onmousemove=null; //释放全局捕获 if(oImg.releaseCapture){ oImg.releaseCapture(); } } //清除默认事件 return false; }