拖拽原理

  • 鼠标和Div的相对距离不变
  • 三大事件
  • 把拖拽加到document上

拖拽简单点来说就是不停的更改物体到页面左边&顶部的距离!

 

那么如何计算出物体到页面左端的距离呢?

当鼠标按下的时候(onmousedown),我们获取

鼠标距离左边&顶部 的值:clientX、clientY

物体距离左边&顶部的值:offsetLeft、offsetTop

这样我们就知道了,鼠标距离物体左边&顶部的距离,即:clientX - offsetLeft;clientY- offsetTop;

 

当鼠标移动的时候(onmousemove),我们获取

鼠标距离左边&顶部的值:clientX、clientY

同时鼠标距离物体左边&顶部的值已经计算出了,

那么物体距离左边&顶部的值,就会得出物体的left&top值。

 

这就算拖拽!

 

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; 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;
		
		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>