基本拖拽效果,使用 mousedown , mousemove , mouseup实现
1.一个div拖拽效果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>基本拖拽效果</title> <script src="../../common/jquery-1.8.3.min.js"></script> <style> *{ margin:0; padding:0; } .drag{ width:100px; height:100px; background-color:red; position:absolute; top:40px; left:50px; } </style> </head> <body> <div class="drag"></div> </body> <script> $(function(){ var _move = false; var _x,_y; $(".drag").mousedown(function(e){ console.log(e.pageX, e.pageY); _move = true; _x = e.pageX - parseInt($(".drag").css("left")); _y = e.pageY - parseInt($(".drag").css("top")); $(".drag").fadeTo(20,0.5); }) $(document).mousemove(function(e){ if(_move){ var x = e.pageX - _x; var y = e.pageY - _y; $(".drag").css({"left":x,"top":y}); } }).mouseup(function(){ _move = false; $(".drag").fadeTo("fast",1); }) }) </script> </html>
2.多个div单独进行拖拽
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>基本拖拽效果</title> <script src="../../common/jquery-1.8.3.min.js"></script> <style> *{ margin:0; padding:0; } .drag{ width:100px; height:100px; background-color:red; position:absolute; top:40px; left:50px; } </style> </head> <body> <div class="drag"></div> <div class="drag"></div> </body> <script> $(function(){ $(".drag").each(function(){ var _move = false; var _x,_y; var _this = $(this); $(this).mousedown(function(e){ console.log(e.pageX, e.pageY); _move = true; _x = e.pageX - parseInt(_this.css("left")); _y = e.pageY - parseInt(_this.css("top")); _this.fadeTo(20,0.5); }) $(document).mousemove(function(e){ if(_move){ var x = e.pageX - _x; var y = e.pageY - _y; _this.css({"left":x,"top":y}); } }).mouseup(function(){ _move = false; _this.fadeTo("fast",1); }) }) }) </script> </html>