指令碼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 執行個體
以上就是本文的全部內容,希望本文的內容對大家的學習或者工作能帶來一定的協助,同時也希望多多支援幫客之家!