1. 程式人生 > >js實現拖拽功能

js實現拖拽功能

<!doctype html>
<html>

	<head>
		<meta charset="utf-8">
		<title>拖拽功能</title>
	</head>

	<body>
		
		
		<div style="width:100px;height: 100px;background-color: red;
		position:absolute;left:0;top:0;"></div>
		
		<script type="text/javascript">
			    //獲得div
			var div = document.getElementsByTagName('div')[0];

			drag(div);
			
			
			function drag(elem) {
				var disX,
					disY;
		
				elem.onmousedown = function (e) {
					//相容性操作
					var event = e || window.event;
					//滑鼠按下的時候,距離元素的左/上距離     
					disX = event.pageX - parseInt(elem.style.left);     //elem.style.left  返回的是字串 XXXpx,
					disY = event.pageY - parseInt(elem.style.top);		//用parseInt方法可以將數字提取出來
					
					document.onmousemove = function (e) {
						
						var event = e || window.event;
								//滑鼠按下的點(相對document) - 滑鼠按下的點(相對當前點選的元素) 
						elem.style.left = event.pageX - disX + "px";
						elem.style.top = event.pageY - disY + "px";
					}
					//當滑鼠按上時,使move事件失效,這樣元素就不會再跟著移動了
					document.onmouseup = function(e){
						document.onmousemove = null;
					}
				}
			}
		</script>
	</body>

</html>