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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ margin: 0; padding: 0;
} div{ width: 200px; height: 200px; font-size: 50px; line-height: 200px; text-align: center; } #one{ background-color: pink; position: absolute; left: 0; top: 0; } #two{ background-color: skyblue; position: absolute; left: 0; top:0; right: 0; bottom: 0; margin: auto; } </style> </head> <body> <div id="one">1</div> <div id="two">2</div> </body> </html> <script type="text/javascript"> one.onmousedown = function(){ event.preventDefault(); var l = event.clientX - this.offsetLeft; var t = event.offsetY; window.onmousemove = function(){ one.style.left = event.clientX - l + "px"; one.style.top = event.clientY - t + "px"; if (crash(one, two)) { two.style.backgroundColor = "green"; }else{ two.style.backgroundColor = "skyblue"; } } } one.onmouseup = function(){ window.onmousemove = null; } function crash(div1, div2){ var xLeft = div2.offsetLeft - div1.offsetWidth; var xRight = div2.offsetLeft + div2.offsetWidth; var yTop = div2.offsetTop - div1.offsetHeight; var yBottom = div2.offsetTop + div2.offsetHeight; if(div1.offsetLeft >= xLeft && div1.offsetLeft <= xRight && div1.offsetTop >= yTop && div1.offsetTop <= yBottom){ return true; }else{ return false; } } </script>
|