1、完美拖拽的思想,具体可以分为:
①计算出鼠标在div的位置,方法为X轴event.clientX-oDiv.offsetLeft;Y轴event.clientY-oDiv.offsetTop;
②计算出鼠标move时候鼠标的X,Y轴,再减去鼠标在div的位置,就是div移动的top和left值
③清除默认事件,ff和chrome可以用return false IE有专用的setCapture() (让本页面所有的事件都集中到一起,例如集中到div上,这样可以防止拖拽的时候文字被选中) 记得鼠标释放的时候要releaseCapture();
④尽量简化代码,把一样的代码放到一个函数里
这样你就做出了一个兼容各种浏览器的完美拖拽代码:
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0'/> <title>拖拽</title> <style> *{margin:0;padding:0;} #div1{width:100px; height:100px; position:absolute; background:red;cursor:move;overflow:hidden;} </style> <script> window.onload=function(){ var oDiv=document.getElementById("div1"); var disX=disY=0; oDiv.onmousedown=function(event){ var event=event||window.event; disX=event.clientX-oDiv.offsetLeft; disY=event.clientY-oDiv.offsetTop; if(oDiv.setCapture){ oDiv.onmousemove=move; oDiv.onmouseup=up; oDiv.setCapture(); return false; }else{ document.onmousemove=move; document.onmouseup=up; return false; } } function move(event){ var event=event||window.event; var l=event.clientX-disX; var t=event.clientY-disY; if(l<0){ l=0; }else if(l>document.documentElement.clientWidth-oDiv.offsetWidth){ l=document.documentElement.clientWidth-oDiv.offsetWidth; } if(t<0){ t=0; }else if(t>document.documentElement.clientHeight-oDiv.offsetHeight){ t=document.documentElement.clientHeight-oDiv.offsetHeight; } oDiv.style.left=l+"px"; oDiv.style.top=t+"px"; } function up(){ if(oDiv.releaseCapture){ oDiv.releaseCapture(); } this.onmousemove=null; this.onmouseup=null; } } </script> </head> <body> sfdsfcsdjkcjsdkljcksdjfk<br> asdjkxcvjixhvjdfjvbdfnvf<br> <div id="div1"></div> </body> </html>