拖拽--吸附
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>拖拽--吸附效果</title> 6 <style> 7 #div1{ 8 width: 100px; 9 height: 100px; 10 background: red; 11 position: absolute; 12 } 13 #div2{ 14 width: 700px; 15 height: 500px; 16 background: #ccc; 17 position: relative; 18 } 19 #div1:hover{ 20 cursor: pointer; 21 } 22 </style> 23 </head> 24 <body> 25 <div id="div2"> 26 <div id="div1"></div> 27 </div> 28 <script> 29 var oDiv = document.getElementById('div1'); 30 var oDiv2 = document.getElementById('div2'); 31 32 var disX = 0; //鼠标的横向距离 33 var disY = 0; //鼠标的纵向距离 34 35 oDiv.onmousedown = function(ev){ 36 var oEvent = ev || event; 37 disX = oEvent.clientX - oDiv.offsetLeft; 38 disY = oEvent.clientY - oDiv.offsetTop; 39 40 document.onmousemove = function(ev){ 41 var oEvent = ev || event; 42 var l = oEvent.clientX - disX; //div1的横向距离 43 var t = oEvent.clientY - disY; ////div1的纵向距离 44 45 if(l<50){ //div1从div2左边被拖出去 吸附效果 46 l = 0; 47 }else if(l > oDiv2.offsetWidth - oDiv.offsetWidth){ 48 l = oDiv2.offsetWidth - oDiv.offsetWidth; 49 } 50 if(t<50){ //div1从div2上边被拖出去 51 t = 0; 52 }else if(t>oDiv2.offsetHeight - oDiv.offsetHeight){ 53 t = oDiv2.offsetHeight - oDiv.offsetHeight; 54 } 55 56 //根据最新的鼠标坐标来确定div的坐标 57 oDiv.style.left = l + 'px'; 58 oDiv.style.top = t + 'px'; 59 } 60 61 document.onmouseup = function(ev){ 62 document.onmousemove = null; 63 document.onmouseup = null; 64 } 65 66 //解决火狐拖拽的bug,取消默认事件 67 return false; 68 } 69 </script> 70 </body> 71 </html>