首先我们应用上次的内容——方块拖拽,利用方块拖拽来让两个方块进行碰撞。
我们可以先定义两个正方形方块,红色的div1,绿色的div2,我们来实现当div1碰撞div2时div2的颜色变为黄色
HTML代码如下:定义方块
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 7 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 <title>Document</title> 9 <style> 10 body { 11 margin: 0; 12 } 13 #div1 { 14 width: 100px; 15 height: 100px; 16 background: red; 17 position: absolute; 18 left: 0; 19 top: 0; 20 } 21 22 #div2 { 23 width: 100px; 24 height: 100px; 25 background: green; 26 position: absolute; 27 left: 500px; 28 top: 200px; 29 } 30 </style> 31 </head> 32 33 <body> 34 <div id="div1"></div> 35 <div id="div2"></div> 36 </body> 37 38 </html>
利用上个文章的的拖拽内容:令div1可以拖拽
1 <script> 2 var div1 = document.getElementById('div1') 3 var div2 = document.getElementById('div2') 4 5 div1.onmousedown = function (event) { 6 var chaX = event.clientX - div1.offsetLeft 7 var chaY = event.clientY - div1.offsetTop 8 9 document.onmousemove = function (event) { 10 div1.style.left = event.clientX - chaX + 'px' 11 div1.style.top = event.clientY - chaY + 'px' 12 } 13 14 document.onmouseup = function () { 15 document.onmousemove = null 16 } 17 18 19 } 20 21 22 </script>
因为我们每次拖拽都要判断是否碰撞,我们的碰撞代码应该放在移动的里面
添加后:
1 <script> 2 var div1 = document.getElementById('div1') 3 var div2 = document.getElementById('div2') 4 5 div1.onmousedown = function (event) { 6 var chaX = event.clientX - div1.offsetLeft 7 var chaY = event.clientY - div1.offsetTop 8 9 document.onmousemove = function (event) { 10 div1.style.left = event.clientX - chaX + 'px' 11 div1.style.top = event.clientY - chaY + 'px' 12 13 if (div1.offsetLeft + div1.offsetWidth < div2.offsetLeft || 14 div2.offsetLeft + div2.offsetWidth < div1.offsetLeft || 15 div1.offsetTop + div1.offsetHeight < div2.offsetTop || 16 div2.offsetTop + div2.offsetHeight < div1.offsetTop 17 ) { 18 div2.style.backgroundColor = '' 19 } else { 20 div2.style.backgroundColor = 'yellow' 21 } 22 23 } 24 document.onmouseup = function () { 25 document.onmousemove = null 26 } 27 } 28 29 </script>
可以看到我们在移动的代码里添加了判断条件
让div1的左边距加上div1的宽度小于div2的左边距,让div2的左边距加上div2的宽度小于div1的左边距,让div1的上边距加上div1的高度小于div2的上边距,让div2的上边距加上div2的高度小于div1的上边距,满足这些条件就是未碰上。