原生JS實現拖動功能

來源:互聯網
上載者:User

標籤:

代碼:

 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實現拖動功能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.