1. 程式人生 > 其它 >js碰撞事件

js碰撞事件

兩個盒子碰撞發生顏色改變:

<html>:

<divid="div1"></div> <divid="div2"></div>

<css>:

body{ margin:0; } #div1{ width:200px; height:200px; background-color:rgb(51,255,0); position:absolute; left:0; top:0; } #div2{ width:200px; height:200px; background-color:rgb(71,0,163); position:absolute; left:500px; top:200px; } <js>:
//獲得按鈕元素 vardiv1=document.getElementById("div1"); vardiv2=document.getElementById("div2"); //給按鈕增加點選事件。 functioncrash(obj1,obj2){ leta=obj1.offsetLeft+obj1.offsetWidth; letb=obj2.offsetLeft+obj2.offsetWidth; letc=obj1.offsetLeft; obj1.offsetTop+obj1.offsetHeight>=obj2.offsetTop&& obj1.offsetTop<=obj2.offsetTop+obj2.offsetHeight&& a>=obj2.offsetLeft&& c<=b ?(obj2.style.background="red") :(obj2.style.background="rgb(71,0,163)"); }


functionmove(obj){ obj.onmousedown=function(){ varchaX=event.clientX-obj.offsetLeft; varchaY=event.clientY-obj.offsetTop;
document.onmousemove=function(event){ obj.style.left=event.clientX-chaX+"px"; obj.style.top=event.clientY-chaY+"px"; crash(div1,div2) };
document.onmouseup=function(){ document.onmousemove=null; }; }; } //封裝完成後輸出 move(div1) move(div2)