首页 > 代码库 > 原生JS实现拖动功能

原生JS实现拖动功能

代码:

 1 function drag(id){ 2  3     var obj = document.getElementById(id), 4         resultX = 0, 5         resultY = 0; 6  7     function getPos(t){ 8         var offsetLeft = 0, 9             offsetTop = 0,10             offsetParent = t;11 12         while(offsetParent){13             offsetLeft+=offsetParent.offsetLeft;14             offsetTop+=offsetParent.offsetTop;15             offsetParent = offsetParent.offsetParent;16         }17 18         return {‘top‘:offsetTop,‘left‘:offsetLeft};19     }20 21     function core(){22 23         var width = document.body.clientWidth || document.documentElement.clientWidth,24             height = document.body.clientHeight || document.documentElement.clientHeight;25             maxWidth = width - obj.offsetWidth,26             maxHeight = height - obj.offsetHeight;27 28         (resultX >= maxWidth)?  obj.style.left = maxWidth+‘px‘ :  obj.style.left = resultX +‘px‘;29         (resultY >= maxHeight)?   obj.style.top = maxHeight +‘px‘ : obj.style.top = resultY +‘px‘;30 31         obj.onmousedown=function(e){32             var e = e || window.event,33                 coordX = e.clientX,34                 coordY = e.clientY,35                 posX = getPos(obj).left,36                 posY = getPos(obj).top;37 38             obj.setCapture && obj.setCapture();39             document.onmousemove=function(e){40 41                 var ev = e || window.event,42                     moveX = ev.clientX,43                     moveY = ev.clientY;44 45                 resultX = moveX - (coordX - posX);46                 resultY = moveY - (coordY - posY);47 48                 (resultX > 0 )?((resultX < maxWidth)?obj.style.left = resultX+‘px‘ : obj.style.left = maxWidth+‘px‘) : obj.style.left = ‘0px‘; 49                 (resultY > 0 )?((resultY < maxHeight)?obj.style.top = resultY+‘px‘ : obj.style.top = maxHeight+‘px‘) : obj.style.top = ‘0px‘; 50 51             };52         };53         document.onmouseup=function(){54             document.onmousemove = null;55             obj.releaseCapture && obj.releaseCapture();56         };57         obj.onmouseup=function(e){58             var e = e || window.event;59             document.onmousemove = null;60             obj.releaseCapture && obj.releaseCapture();61         };62     }63     core();64     window.onresize = core;65 }

使用方式:

1 drag(‘box‘);

 

原生JS实现拖动功能