JAVASCRIPT 完美拖拽类

拖拽是网页中经常用到的控件,因此封装了一个推拽类。

 

查看演示

<script type="text/javascript">
/* new Dragdrop({
 * 		target 	 拖拽元素 HTMLElemnt 必选
 * 		bridge	 指定鼠标按下哪个元素时开始拖拽,实现模态对话框时用到 
 * 		dragX 	 true/false false水平方向不可拖拽 (true)默认
 * 		dragY	 true/false false垂直方向不可拖拽 (true)默认
 * 		area 	 [minX,maxX,minY,maxY] 指定拖拽范围 默认任意拖动
 * 		callback 移动过程中的回调函数
 * });
*/
function dragDrop(option){
	this.target=option.target;
	this.dragX=option.dragX!=false;
	this.dragY=option.dragY!=false;
	this.disX=0;
	this.disY=0;
	this.bridge =option.bridge;
	this.area=option.area;
	this.callback=option.callback;
	this.target.className="drag";
	var _this=this;
	 this.bridge?this.brideg.onmousedown=function(e){ _this.mousedown(e)}:this.target.onmousedown=function(e){ _this.mousedown(e)}
	 	}
	dragDrop.prototype={
		mousedown:function(e){
			var e=e||event;
			 this.disX=e.clientX-this.target.offsetLeft;
			 this.disY=e.clientY-this.target.offsetTop;
			this.target.style.cursor = 'move';
			 if(window.captureEvents){ 
	   	  e.stopPropagation();
          e.preventDefault();}
		  	else{
				e.cancelBubble = true;
				}
			var _this=this;	
			var movehandler = function (e) {
        _this.move(e)
    };
	var uphandler = function (e) {
        _this.mouseup(e)
    };
			document.onmousemove=function(e){_this.move(e)}
			document.onmouseup=function(e){_this.mouseup(e)}
					},
	move:function(e){
				var e=e||event;
				var moveX=e.clientX-this.disX;
				var moveY=e.clientY-this.disY;
				var _this=this;	

				if(this.area){
			moveX < _this.area[0] && (moveX = this.area[0]); //left 最小值
			moveX > _this.area[1] && (moveX = this.area[1]); //left 最大值
			moveY < _this.area[2] && (moveY = this.area[2]); //top 最小值
			moveY > _this.area[3] && (moveY = this.area[3]); //top 最大值					
					}
				this.dragX && (this.target.style.left=moveX+'px');
				this.dragY && (this.target.style.top=moveY+'px');
				if(this.callback){
					var obj = {moveX:moveX,moveY:moveY};
					this.callback.call(this,obj)
					}
			return false
			},
	 mouseup:function (e)
			{
	         var e=e||event;
	         this.target.style.cursor = 'default';
		     var _this=this;
			document.onmousemove=null;
			document.onmouseup=null;

			}	
		}

</script>

</head>

<body>
<div id="box1"></div>
//调用方法:
	var box1=document.getElementById('box1');
    	var d1=new dragDrop({
		target:box1,
		area :[0,document.body.clientWidth-100,0,document.body.clientHeight-100],
		callback:function(obj){
		box1.innerHTML='x:'+obj.moveX;
		}
		})

</body> </html>
posted @ 2012-03-01 17:57  红叶舞秋山  阅读(352)  评论(0编辑  收藏  举报