退拽原理

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			#div1{
				width: 100px;
				height: 100px;
				background: red;
				position: absolute;
			}
		</style>
		<script>
			window.onload=function(){
//				onmousedown:选择元素
//				onmousemove:移动元素
//				onmouseup:释放元素
				
				var oDiv=document.getElementById("div1");
				
				oDiv.onmousedown=function(ev){
					var ev=ev||event;
//				              鼠标的位置-当前div距离浏览器左边的距离
					var disX=ev.clientX-this.offsetLeft;
					var disY=ev.clientY-this.offsetTop;
					document.onmousemove=function(ev){
						var ev=ev||event;
						oDiv.style.left=ev.clientX-disX+"px";
						oDiv.style.top=ev.clientY-disY+"px";
					}
					document.onmouseup=function(){
						document.onmousemove=document.onmouseup=null;
					}
				}
				
				
			}
		</script>
	</head>
	<body>
		<div id="div1"></div>
		<div style="width: 100px;height: 100px;background: green;position: absolute;left: 400px;top: 200px;"></div>
	</body>
</html>

 

posted @ 2018-11-29 09:30  webxy  阅读(109)  评论(0编辑  收藏  举报