網(wǎng)頁上有很多拖曳的操作,比如拖動樹狀列表,可拖曳的圖片等。
1.原生拖放實(shí)現(xiàn)
<!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;//判斷目標(biāo)對象書否處于移動狀態(tài) var _x, _y;//鼠標(biāo)離控件左上角的相對x.y坐標(biāo) $('.drag').click(function(event) { }).mousedown(function(e) {//當(dāng)按下鼠標(biāo)左鍵時 _move = true;//標(biāo)記移動為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) {//監(jiān)聽鼠標(biāo)移動 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實(shí)現(xiàn)拖放
自行實(shí)現(xiàn)拖曳方法比較負(fù)責(zé),jQuery UI提供了可拖曳的事件,允許用戶非常簡單的為一個div添加拖曳效果。
jQuery UI主要通過draggable事件來實(shí)現(xiàn)拖曳功能。
 <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>關(guān)于draggable的API可以參考draggalbe API
以上就是本文的全部內(nèi)容,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,同時也希望多多支持VeVb武林網(wǎng)!
新聞熱點(diǎn)
疑難解答