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 #div1:hover{ 14 cursor: pointer; 15 } 16 </style> 17 </head> 18 <body> 19 文字內容<br /> 20 文字內容<br /> 21 文字內容 22 <div id="div1">文字內容文字內容文字內容文字內容</div> 23 <script> 24 var oDiv = document.getElementById('div1'); 25 26 27 var disX = 0; //鼠標的橫向距離 28 var disY = 0; //鼠標的縱向距離 29 30 oDiv.onmousedown = function(ev){ 31 var oEvent = ev || event; 32 disX = oEvent.clientX - oDiv.offsetLeft; 33 disY = oEvent.clientY - oDiv.offsetTop; 34 35 function mouseMove(ev){ 36 var oEvent = ev || event; 37 var l = oEvent.clientX - disX; //div1的橫向距離 38 var t = oEvent.clientY - disY; ////div1的縱向距離 39 40 //根據最新的鼠標坐標來確定div的坐標 41 oDiv.style.left = l + 'px'; 42 oDiv.style.top = t + 'px'; 43 } 44 45 46 function mouseUp(ev){ 47 this.onmousemove = null; 48 this.onmouseup = null; 49 50 if(oDiv.releaseCapture){ 51 oDiv.releaseCapture(); 52 } 53 } 54 55 if(oDiv.setCapture){ 56 //IE 57 oDiv.onmousemove = mouseMove; 58 59 oDiv.onmouseup = mouseUp; 60 61 oDiv.setCapture(); //事件捕獲,解決IE9以下兼容問題 62 }else{ 63 //chrome、ff 64 document.onmousemove = mouseMove; 65 66 document.onmouseup = mouseUp; 67 } 68 69 //解決火狐拖拽的bug,取消默認事件 70 return false; //解決chrome、ff、IE9的兼容問題 71 } 72 </script> 73 </body> 74 </html>
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。