鼠标拖动div代码

 原理:鼠标单击title时候给需要移动的div块添加mouseMove与mouseUp

  在mouseMove中不断改变 div 坐标,使之随着运动

   mouseUp的时候移除div的 mousemove 和mouseup 事件 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>drag</title>
<script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
var drag=new dragMing("#title","#main");
function dragMing(idORclass1,idORclass2){
   var obj=this;
   this.idORclass1=idORclass1;
   this.idORclass2=idORclass2;
   this.deltaX=0;
   this.deltaY=0;
   function dragStart(dragEvent){
		 obj.deltaX=dragEvent.clientX-$(obj.idORclass2).offset().left;
		 obj.deltaY=dragEvent.clientY-$(obj.idORclass2).offset().top;
		 $(document).bind("mousemove",dragMove);  
		 $(document).bind("mouseup",dragStop);
		 dragEvent.preventDefault();
   }
   function dragMove(dragEvent){
     $(obj.idORclass2).css({
		 "left":(dragEvent.clientX-obj.deltaX)+"px",
		 "top" :(dragEvent.clientY-obj.deltaY)+"px",
       })
	 dragEvent.preventDefault();
   }
   function dragStop(){
			 $(document).unbind("mousemove",dragMove);
			 $(document).unbind("mouseup",dragStop);
   }
	 $(document).ready(function(){
          $(obj.idORclass1).bind("mousedown",dragStart);
	 })
}
</script>
</head>
<style type="text/css">
	body{
		margin:0;
		padding:0;
	}
	#main{
		position:absolute;
		width:100px;
		height:200px;
		color:red;
		background-color:yellow;
	}
	#title{
		width:100px;
		height:20px;
		background-color:#00FF00;
		border:5px;
	
	}
</style>
<body>
<div id="main">
	<div id="title"></div>
</div>

</body>
</html>

相关推荐