1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
  2. <html> 
  3. <head> 
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
  5. <title>draggable</title> 
  6. <style type="text/css"> 
  7. .ui-draggable{ 
  8.     position: absolute; 
  9.     cursor: move; 
  10. .ui-draggable-opacity{ 
  11.     filter:alpha(opacity =50); 
  12.     -moz-opacity:0.5 ; 
  13.     -khtml-opacity: 0.5; 
  14.     opacity: 0.5; 
  15. </style> 
  16. </head> 
  17. <body> 
  18. <div id='demo' style='width:200px;height:100px;background: #ccc;'> 
  19.     drag me! 
  20. </div> 
  21. <script type="text/javascript" src='http://code.jquery.com/jquery-latest.min.js'></script> 
  22. <script type="text/javascript"> 
  23. /** 
  24.  * jquery 实现拖动 
  25.  * @author huxiaoqi 
  26.  */ 
  27. (function($){ 
  28.     $.fn.draggable = function(){ 
  29.         var self = $(this); 
  30.         self.addClass('ui-draggable'); 
  31.         var width = self.width(); 
  32.         var height = self.height(); 
  33.         var position = self.position(); 
  34.         var pos = { 
  35.                     mouseX:0, 
  36.                     mouseY:0, 
  37.                     offsetX:0, 
  38.                     offsetY:0 
  39.                   }; 
  40.  
  41.         self.bind({'mousedown':function(e){ 
  42.                 self.addClass('ui-draggable-opacity'); 
  43.                 position = self.position(); 
  44.                 pos.offsetX = e.pageX - position.left; 
  45.                 pos.offsetY = e.pageY - position.top; 
  46.             //记录鼠标位置和目标位置的相对位置 
  47.                 $(document).bind('mousemove',function(e){ 
  48.                     position = self.position(); 
  49.                     pos.mouseX = e.pageX; 
  50.                     pos.mouseY = e.pageY; 
  51.                     self.moveTo(pos.mouseX - pos.offsetX , pos.mouseY - pos.offsetY); 
  52.                 }); 
  53.             }, 
  54.             'mouseup':function(e){ 
  55.                 $(document).unbind('mousemove'); 
  56.                 self.removeClass('ui-draggable-opacity'); 
  57.             } 
  58.         }); 
  59.         self.moveTo = function(x,y){ 
  60.             self.css({'left':x,'top':y}); 
  61.             return self; 
  62.         }; 
  63.     }; 
  64. })(jQuery); 
  65. $('#demo').draggable(); 
  66. </script> 
  67. </body> 
  68. </html>