1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title>矩形碰撞01</title>
6 <style type="text/css">
7 * { margin: 0; padding: 0; }
8 div { position: absolute; width: 100px; height: 100px; font-size: 50px; line-height: 100px; text-align: center; }
9 #move_box { background-color: #40E0D0; cursor: pointer; }
10 #hit_box { left: 200px; top: 200px; background-color: #98FB98; }
11 </style>
12 </head>
13 <body>
14 <div id="move_box">移動</div>
15 <div id="hit_box">被撞</div>
16 </body>
17 <script type="text/javascript">
18
19 var moveBox = document.getElementById("move_box"); 20 var hitBox = document.getElementById("hit_box"); 21
22 //移動對象去進行碰撞
23 moveBox.onmousedown = function (event){ 24
25 var event = event || window.event; 26
27 var disX = event.clientX - moveBox.offsetLeft; 28 var disY = event.clientY - moveBox.offsetTop; 29
30 document.onmousemove = function (event){ 31
32 var event = event || window.event; 33
34 var x = event.clientX - disX; 35 var y = event.clientY - disY; 36
37 var moveLeft = moveBox.offsetLeft; //移動對象的左偏移
38 var moveRight = moveLeft + moveBox.offsetWidth; //移動對象的右偏移=左偏移+自身寬度
39 var moveTop = moveBox.offsetTop; //移動對象的上偏移
40 var moveBottom = moveTop + moveBox.offsetHeight; //移動對象的下偏移=上偏移+自身高度
41
42 var hitLeft = hitBox.offsetLeft; //被撞對象的左偏移
43 var hitRight = hitLeft + hitBox.offsetWidth; 44 var hitTop = hitBox.offsetTop; 45 var hitBottom = hitTop + hitBox.offsetHeight; 46
47 if (moveBottom < hitTop || moveRight < hitLeft || moveTop > hitBottom || moveLeft > hitRight){ 48 hitBox.style.backgroundColor = "#98FB98"; 49 hitBox.innerHTML = "被撞"; 50 }else{ 51 hitBox.style.backgroundColor = "#FF6347"; 52 hitBox.innerHTML = "撞上"; 53 } 54
55 moveBox.style.left = x + "px"; 56 moveBox.style.top = y + "px"; 57 } 58
59 //中止移動
60 document.onmouseup = function (){ 61 document.onmousemove = null; 62 } 63
64 return false; 65 } 66 </script>
67 </html>