Javascript:簡單拖拽效果的實現

來源:互聯網
上載者:User

標籤:

  

核心代碼:

/**完成一個拖拽事件由三大事件組成:*1:onmousedown:選擇元素*2:onmousemove:移動元素*3:onmouseup:釋放元素 */function drag(obj){obj.onmousedown=function(ev){var ev=ev || event;var disX=ev.clientX-this.offsetLeft;var disY=ev.clientY-this.offsetTop;//IE下選中文字後移動時,文字跟著移動的BUGif(obj.setCapture){       obj.setCapture();}document.onmousemove=function(ev){            //此時採用document,而不採用obj,是因為採用obj時,滑鼠移動太快,obj會跟不上滑鼠的速度,而採用document,只要滑鼠不脫離文檔流,obj都可以靈活移動      var L=ev.clientX-disX;      var T=ev.clientY-disY;      var maxL=document.documentElement.clientWidth-obj.offsetWidth;      if(L<200){      //設定移動邊界值      //直接改變L值,比如200,可以實現磁性吸附效果      L=0;      } else if(L>maxL){        L=maxL;      }      obj.style.left=L+‘px‘;      obj.style.top=T+‘px‘;}return false;}obj.onmouseup=function(){document.onmousemove=document.onmouseup=null;    if(obj.releaseCapture){       obj.releaseCapture();}return false;}}

 

DEMO:

線上示範:http://codepen.io/anon/pen/OVBEpM

<div id="words">這是文字這是文字這是文字這是文字這是文字</div> <div id="div1"></div><script>var oDiv=document.getElementById(‘div1‘);var oWords=document.getElementById(‘words‘);drag(oDiv);drag(oWords);</script>

  

 

Javascript:簡單拖拽效果的實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.