碰撞动画
发表于|更新于
|阅读量:
碰撞检测
通过对两个div周围的上下左右进行检查,判断是否碰到
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| <!DOCTYPE html> <html lang="en">
<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> #box { width: 200px; height: 200px; background-color: gainsboro; position: absolute; left:50%; margin-left: -100px; top:50%; margin-top: -100px; } #move{ width: 100px; height: 100px; background-color: red; position: absolute; } </style> <script> window.onload = function () { var box = document.getElementById("box") var move = document.getElementById("move")
move.onmousedown = function(ev) { ev = ev || event; var t = ev.clientY - move.offsetTop; var l = ev.clientX - move.offsetLeft; document.onmousemove = function(ev) { ev = ev || evnet;
var left = ev.clientX - l; var top = ev.clientY - t;
move.style.left = left + "px"; move.style.top = top + "px"
if(left + move.offsetWidth < box.offsetLeft || left >box.offsetLeft + box.offsetWidth || top + move.offsetHeight < box.offsetTop || top > box.offsetTop + box.offsetHeight ) { console.log('no'); box.style.background = 'gainsboro' } else { console.log('yes'); box.style.background = 'orange' } } } move.onmouseup = function () { document.onmousemove = null; } } </script> </head>
<body> <div id="box"></div> <div id="move"></div> </body>
</html>
|