1 /**
  2  * vui 拖拽
  3  * @constructor
  4  * @author putaoshu@126.com
  5  * @date 2012-07-19
  6  * @param {Object} obj 主对象
  7  * @param {Object} options 组件配置
  8  * @param {Boolean} options.lockX   false 锁定X
  9  * @param {Boolean} options.lockY   false 锁定Y
 10  * @param {Function} options.start   null 开始拖动回调
 11  * @param {Function} options.drag   null 拖动中回调
 12  * @param {Function} options.end   null 结束拖动回调
 13  * @param {Number} options.maxLeft null max left
 14  * @param {Number} options.maxRight null max right
 15  * @param {Number} options.maxTop null max top
 16  * @param {Number} options.maxBottom null max bottom
 17  * @example vui.drag($('.content'),{
 18 	 lockX:true,
 19 	 maxTop:0,
 20 	 maxBottom:200
 21 });
 22  */
 23  
 24 vui.drag = function(obj,options){
 25 	options = $.extend({
 26 		lockX : false,//锁定X
 27 		lockY : false,//锁定Y
 28 		start : null,//开始拖动回调
 29 		drag : null,//拖动中回调
 30 		end : null,//结束拖动回调
 31 		maxLeft:null,
 32 		maxRight:null,
 33 		maxTop:null,
 34 		maxBottom:null
 35 	},options);
 36 
 37 	 var o = {
 38 		dragging:null,
 39 		init:function(){
 40 			 this.bind();
 41 		},
 42 		diffX:0,
 43 		diffY:0,
 44 		unbind:function(){
 45 			 $(document).unbind('mousedown').unbind('mousemove').unbind('mouseup');
 46 		},
 47 		bind:function(){
 48 			 var self = this;
 49 			$(document).bind('mousedown',function(event){
 50 				  if (event.target.className == obj.attr('class') ){
 51 					self.dragging = true;
 52 					self.diffX = event.clientX - obj.offset().left;
 53 					self.diffY = event.clientY - obj.offset().top;
 54 					if(options.start != null){
 55 						options.start.call();
 56 					}
 57 				 }
 58 			})
 59 			.bind('mousemove',function(event){
 60 				if (self.dragging){
 61 					var top,left;
 62 					if (!options.lockY){
 63 						top  = event.clientY - self.diffY;
 64 						if (options.maxTop!=null && top < options.maxTop){
 65 							top = options.maxTop;
 66 						}
 67 						if (options.maxBottom!=null && top > options.maxBottom){
 68 							top = options.maxBottom;
 69 						}
 70 						obj.css({top:top})
 71 					}
 72 					if (!options.lockX){
 73 						left  = event.clientX - self.diffX;
 74 						if (options.maxLeft!=null && top < options.maxLeft){
 75 							top = options.maxLeft;
 76 						}
 77 						if (options.maxRight!=null && top > options.maxRight){
 78 							top = options.maxRight;
 79 						}
 80 						obj.css({left:left})
 81 					}
 82 					var arg = [top,left];
 83 					if (top==undefined){
 84 						arg = left;
 85 					}
 86 					if (left==undefined){
 87 						arg = top;
 88 					}
 89 					if(options.drag != null){
 90 						options.drag.call(null,arg);
 91 					}
 92 				}
 93 			})
 94 			.bind('mouseup',function(event){
 95 				 if(options.end != null){
 96 					options.end.call();
 97 				}
 98 				 self.dragging = false;
 99 			});
100 		}
101 	 }
102 	 o.init();
103 }
104 
105