拖拽

<!DOCTYPE HTML>
<html lang="en-US">
<head>
	<meta charset="UTF-8">
	<title></title>
	<style type="text/css">
		#box {width:100px; height:100px; background:red;position:absolute;}
	</style>
</head>
<body>
	
	<div id="box">
		
	</div>
	<script type="text/javascript">
		
		var box = document.getElementById('box');
		//定義全局變量
		var divX = 0; //div的x座標
		var divY = 0; //div的y座標
		var mouseX = 0; //鼠標的x座標
		var mouseY = 0; //屬性的y座標
		var sw = false; //表示開關

		//綁定mouserdown事件
		box.onmousedown = function(evt){
			var e = evt || window.event;
			console.log(e);
			//獲取div的位置
			divX = this.offsetLeft; //值是沒有單位的
			divY = this.offsetTop;
			//獲取鼠標所處的位置
			mouseX = e.clientX;
			mouseY = e.clientY;
			//開啓開關
			sw = true;
		}

		//綁定mousemove事件
		document.onmousemove = function(evt){
			var e = evt || window.event;
			//只有開啓了開關,纔有效 
			if (sw) {
				var disX = e.clientX - mouseX;
				var disY = e.clientY - mouseY;
				//console.log(disX,disY);
				//利用相對論,設置div的left和top值就能夠了
				box.style.left = divX + disX + "px"; //注意加單位
				box.style.top = divY + disY + "px"; 
			}	
		}
		//綁定mouseup事件
		document.onmouseup = function(){
			sw = false;
		}
	
	</script>
</body>
</html>
相關文章
相關標籤/搜索