之前实现元素的拖拽很多都是通过js手写的,后来发现使用jqueryui实现,简单特别多,而且能完成很多附加功能。
首先是最基本的用法。$(" ").draggable()就能实现指定元素的拖拽
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="//apps.bdimg.com/libs/jqueryui/1.10.4/css/jquery-ui.min.css"> <script src="//apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//apps.bdimg.com/libs/jqueryui/1.10.4/jquery-ui.min.js"></script> </head> <body> <div class="selector" style="width: 300px;height: 300px;background-color: lightsalmon;" > </div> </body> <script type="text/javascript"> $(function(){ $( ".selector" ).draggable(); }) </script> </html>
有时候,我们需要拖动元素内部某一块禁止拖动,又有些时候,我们只需要某一块内容能被拖动。
可以借助属性handle和cancel来实现,handle是可以指定元素,只有被指定的元素能拖动。cancel是刚好相反
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="//apps.bdimg.com/libs/jqueryui/1.10.4/css/jquery-ui.min.css"> <script src="//apps.bdimg.com/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//apps.bdimg.com/libs/jqueryui/1.10.4/jquery-ui.min.js"></script> </head> <body> <div class="handle" style="width: 300px;height: 300px;background-color: lightsalmon;" > <div class="selector1" style="width:100px;height: 100px;background-color: lightseagreen;"></div> <div id="test1" style="width: 100px;height: 100px;background-color: lightgreen;"></div> </div> <div class="cancel" style="width: 300px;height: 300px;background-color: lightcyan;" > <div class="selector2" style="width:100px;height: 100px;background-color: lightgrey;"></div> <div id="test2" style="width: 100px;height: 100px;background-color: lightpink;"></div> </div> </body> <script type="text/javascript"> $(function(){
//可以同时指定多个,使用逗号隔开 $( ".handle" ).draggable({ handle: ".selector1,#test1" }); $( ".cancel" ).draggable({ cancel: ".selector2,#test2" }); }) </script> </html>