1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta name="description" content="jQuery拖拽div" /> 5 <meta charset="utf-8"> 6 <title>JS Bin</title> 7 <style> 8 #div{ width:200px; height:200px; background:#ccc; position:absolute;} 9 #div h1{ height:30px; line-height:30px; font-size:12px; text-align:center;background: #f1f1f1;border-bottom: 1px solid #ccc;} 10 </style> 11 <script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.10.2/jquery-1.10.2.js"></script> 12 13 </head> 14 <body> 15 <div id="div"><h1>标题</h1></div> 16 <script> 17 $.fn.setDrag = function(options){ 18 var defaults = { 19 }, 20 that = $(this), 21 opts = $.extend({}, defaults, options), 22 doc = $(document), 23 width = $(window).width(), 24 height = $(window).height(), 25 startX = 0, 26 startY = 0, 27 lastX = 0, 28 lastY = 0, 29 box = that.parent(), // handler.parentNode 30 handler = that[0], 31 drag = { 32 down: function(e){ 33 that.css('cursor', 'move'); 34 startX = e.clientX - parseInt(box.css('left')); 35 startY = e.clientY - parseInt(box.css('top')); 36 this.setCapture && this.setCapture(); // IE to prevent fast drag losing of object 37 doc.on('mousemove', drag.move); 38 doc.on('mouseup', drag.up); 39 return false; // chrome to prevent rolling screen, and the loss of the mouse move style 40 }, 41 move: function(e){ 42 lastX = e.clientX - startX; 43 lastY = e.clientY - startY; 44 lastX = Math.max(0, Math.min(width - box.outerWidth(), lastX)); 45 lastY = Math.max(0, Math.min(height - box.outerHeight() - 1, lastY)); 46 box.css({'top': lastY + 'px', 'left': lastX + 'px'}); 47 window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); // cancel the selected text 48 e.stopPropagation(); 49 }, 50 up: function(){ 51 // that.css('cursor', 'auto'); 52 doc.off('mousemove', drag.move); 53 doc.off('mouseup', drag.up); 54 handler.releaseCapture && handler.releaseCapture(); // IE to prevent fast drag losing of object 55 } 56 }; 57 that.on('mousedown', drag.down); 58 } 59 60 $('#div h1').setDrag(); 61 </script> 62 63 </body> 64 </html>