<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="keywords" content="div移动">
<title>div移动</title>
</head>
<body>
    <div id="div" style="width:200px; position:absolute; height:200px; background-color:#F90; "></div>			<!-- 做一个div   0.0 -->	
</body>
</html>
<script type="text/javascript">
	var div = document.getElementById('div');
	document.onmousedown = function(e)		//鼠标点击事件
	{
		e = e || window.event;
		var tops = document.getElementById('div').offsetTop;		//div四个角的坐标(200可变动)
		var lefts = document.getElementById('div').offsetLeft;
		var rights = lefts+200;
		var bottoms = tops+200;
		var mousex = e.pageX || e.clientX;			//点击时的鼠标位置
		var mousey = e.pagey || e.clientY;
		var topz = document.getElementById('div').getBoundingClientRect().top;		//获取div的左上位置
		var leftz = document.getElementById('div').getBoundingClientRect().left;
		if((mousex > lefts && mousex < rights)&&(mousey > tops && mousey < bottoms))
		{		//判断鼠标点击时是否在div中
			document.onmousemove = function(e)		//鼠标滑动事件
			{
				var mousexx = e.pageX || e.clientX;			//获取实时鼠标位置
				var mouseyy = e.pagey || e.clientY;
				var xx = mousexx - mousex;					//求移动的距离
				var yy = mouseyy - mousey;
				leftzz = leftz + xx;			
				topzz = topz + yy;
				div.style.left = leftzz +"px";				//对div的左上角进行计算,与鼠标移动的距离相同
				div.style.top = topzz +"px";
			}
		}
	}
	document.onmouseup = function(){		//鼠标抬起将滑动事件解除
		document.onmousemove = null;
	}
</script>

  

 posted on 2016-10-11 16:20  の西瓜  阅读(340)  评论(0编辑  收藏  举报