<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="author" content="智能社 - zhinengshe.com" /> <meta name="copyright" content="智能社 - zhinengshe.com" /> <title>智能社 - www.zhinengshe.com</title> <style> div{ position:absolute;left:0;top:0; width:100px; height:100px; background:green;} </style> <script> window.onload = function(){ var oDiv1 = document.getElementById("div1"); var aDiv = document.getElementsByTagName("div"); for(var i = 0; i < aDiv.length; i++){ drag(aDiv[i]); } function drag(oDiv1){ oDiv1.onmousedown = function(ev){ var oEvent = ev || event; var disX = oEvent.clientX - oDiv1.offsetLeft; var disY = oEvent.clientY - oDiv1.offsetTop; document.onmousemove = function(ev){ var oEvent = ev || event; for(var i = 0; i < aDiv.length; i++){ if(oDiv1 == aDiv[i]) continue; if(collTest(oDiv1,aDiv[i])){ aDiv[i].style.background = "red"; } else { aDiv[i].style.background = "green"; } } oDiv1.style.left = oEvent.clientX - disX + "px"; oDiv1.style.top = oEvent.clientY - disY + "px"; }; document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null; oDiv1.releaseCapture && oDiv1.releaseCapture(); }; oDiv1.setCapture && oDiv1.setCapture(); return false; }; } function collTest(obj1,obj2){ var l1 = obj1.offsetLeft; var t1 = obj1.offsetTop; var r1 = l1 + obj1.offsetWidth; var b1 = t1 + obj1.offsetHeight; var l2 = obj2.offsetLeft; var t2 = obj2.offsetTop; var r2 = l2 + obj2.offsetWidth; var b2 = t2 + obj2.offsetHeight; if(r1 < l2 || b1 < t2 || l1 > r2 || t1 > b2){//没碰到 return false; } else { return true; } } }; </script> </head> <body> <div id="div1"></div> <div style="left:200px;top:100px;"></div> <div style="left:400px;top:100px;"></div> <div style="left:600px;top:100px;"></div> <div style="left:800px;top:100px;"></div> <div style="left:200px;top:400px;"></div> <div style="left:400px;top:400px;"></div> <div style="left:600px;top:400px;"></div> <div style="left:800px;top:400px;"></div> </body> </html>
原文:http://www.cnblogs.com/heboliufengjie/p/4797037.html