- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title > 拖拽 </title>
- <style>
- *{
- margin:0;
- padding:0;
- }
- div{
- position: absolute;
- left:0;
- top:0;
- width: 100px;
- height: 100px;
- background: red;
- }
- </style>
- </head>
- <body>
- <div id="div"></div>
- <script>
- var oDiv=document.getElementById('div');
- oDiv.onmousedown=down;
- function processThis(fn,obj){
- return function(e){
- fn.call(obj,e)
- }
- }
- function down(e){
- e=e||window.event;
- this.x=this.offsetLeft;
- this.y=this.offsetTop;
- this.mx= e.clientX;
- this.my= e.clientY;
- if(this.setCapture){
- this.setCapture();
- this.onmousemove=processThis(move,this);
- this.onmouseup=processThis(up,this);
- }else{
- document.onmousemove=processThis(move,this);
- document.onmouseup=processThis(up,this);
- }
- }
- function move(e){
- e=e||window.event;
- this.style.left=this.x+(e.clientX-this.mx)+'px';
- //this.x: 移动前 offsetLeft 值;(e.clientX-this.mx): 鼠标横向移动的距离, 即盒子横向移动的距离
- this.style.top=this.y+(e.clientY-this.my)+'px';
- //this.y: 移动前 offsetTop 值;(e.clientX-this.mx): 鼠标纵向移动的距离, 即盒子纵向移动的距离
- }
- function up(){
- if(this.releaseCapture){
- this.releaseCapture();
- this.onmousemove=null;
- this.onmouseup=null;
- }else{
- document.onmousemove=null;
- document.onmouseup=null;
- }
- }
- </script>
- </body>
- </html>
来源: http://www.qdfuns.com/article/40901/0c484644efe03bf0acd4e3bf7b347ef3.html