原生JS拖拽
放代码:
给要拖拽的盒子设置:决定定位
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Document</title> 7 <style> 8 #div1 { 9 width: 500px; 10 height: 500px; 11 position: absolute; 12 background-color: pink; 13 } 14 </style> 15 </head> 16 <body> 17 <div id="div1"></div> 18 <script> 19 window.onload=function() 20 { 21 var oDiv=document.getElementById('div1'); 22 oDiv.onmousedown=function(ev) 23 { 24 var oEvent=ev||event; 25 var x=0; 26 var y=0; 27 x=oEvent.clientX-oDiv.offsetLeft; 28 y=oEvent.clientY-oDiv.offsetTop; 29 document.onmousemove=function(ev) 30 { 31 var oEvent=ev||event; 32 var out1=oEvent.clientX-x; 33 var out2=oEvent.clientY-y; 34 35 var oWidth=document.documentElement.clientWidth-oDiv.offsetWidth; 36 var oHeight=document.documentElement.clientHeight-oDiv.offsetHeight; 37 38 if(out1<0) 39 {out1=0;} 40 else if (out1>oWidth) 41 { 42 out1=oWidth; 43 } 44 45 46 if(out2<0) 47 {out2=0;} 48 else if (out2>oHeight) 49 { 50 out2=oHeight; 51 } 52 53 oDiv.style.left=out1+'px'; 54 oDiv.style.top=out2+'px'; 55 } 56 document.onmouseup=function() 57 { 58 document.onmousemove=null; 59 document.onmouseup=null; 60 } 61 return false;//解决firefox低版本的bug问题 62 } 63 } 64 </script> 65 </body> 66 </html>
觉得有一句话非常有道理:学习是一个不断抄袭和重复的过程
记录自己的采坑之路,需要时方便查找