指令碼div實現拖放功能(兩種),div拖放

來源:互聯網
上載者:User

指令碼div實現拖放功能(兩種),div拖放

網頁上有很多拖曳的操作,比如拖動樹狀列表,可拖曳的圖片等。

1.原生拖放實現

<!doctype html><html lang="en"><head> <meta charset="utf-8"> <title>jQuery UI Autocomplete - Default functionality</title> <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="external nofollow" > <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <style> .drag{ width: 200px; height: 200px; background-color: red; position: absolute; left:0; top:0; } </style> <script> $(function() { var _move = false;//判斷目標對象書否處於移動狀態 var _x, _y;//滑鼠離控制項左上方的相對x.y座標 $('.drag').click(function(event) { }).mousedown(function(e) {//當按下滑鼠左鍵時 _move = true;//標記移動為true,開始移動 _x = e.pageX - parseInt($('.drag').css('left'));//得到左上方的x的位置 _y = e.pageY - parseInt($('.drag').css('top'));//得到左上方的y的位置 $('.drag').fadeTo('20', 0.5);//單擊後開始拖動  });  $(document).mousemove(function(e) {//監聽滑鼠移動 if(_move) { var x = e.pageX - _x;//計算移動的距離 var y = e.pageY - _y; $('.drag').css({top:y, left:x}); } }).mouseup(function() { _move = false; $('.drag').fadeTo('fast', 1); }); }); </script></head><body> <div class="drag"></div></body></html>

2 jQuery UI draggable實現拖放

自行實現拖曳方法比較負責,jQuery UI提供了可拖曳的事件,允許使用者非常簡單的為一個div添加拖曳效果。

jQuery UI主要通過draggable事件來實現拖曳功能。

 <script> $(document).ready(function(e) {  $('.drag').draggable({cursor: 'move'});  $('#enable').click(function(e) { $('.drag').draggable('enable');  });  $('#disable').click(function(event) { $('.drag').draggable('disable');  });  $('#deatroy').click(function(event) { $('.drag').draggable('destroy');  }); }) </script></head><body> <button id="enable">enable</button> <button id="disable">disable</button> <button id="destroy">destroy</button> <div class="drag"> <p>請拖動我!</p>  </div></body>

關於draggable的API可以參考draggalbe API

draggable 執行個體

以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的協助,同時也希望多多支援幫客之家!

聯繫我們

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