1. 程式人生 > >拖拽的封裝

拖拽的封裝

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			#div1{
				width: 100px;
				height: 100px;
				background: red;
				position: absolute;
			}
			#img1{
				position: absolute;
			}
		</style>
<script>
window.onload=function(){
	
	var oDiv=document.getElementById("div1");
	var oImg=document.getElementById("img1");
	drag(oImg);
	drag(oDiv);
	function drag(obj){
			obj.onmousedown=function(ev){
			var ev=ev||event;
	//				              滑鼠的位置-當前div距離瀏覽器左邊的距離
			var disX=ev.clientX-this.offsetLeft;
			var disY=ev.clientY-this.offsetTop;
	//					IE下:用全域性捕獲就可以實現
			if(obj.setCapture){
				obj.setCapture();
			}
			document.onmousemove=function(ev){
				var ev=ev||event;
				obj.style.left=ev.clientX-disX+"px";
				obj.style.top=ev.clientY-disY+"px";
			}
			document.onmouseup=function(){
				document.onmousemove=document.onmouseup=null;
	//						IE下
				//釋放全域性捕獲 releaseCapture();
				if(obj.releaseCapture){
					obj.releaseCapture();
				}
			}
			return false;
		}
	}
}
</script>
	</head>
	<body>
		<div id="div1"></div>
		<img src="img/1.jpg" id="img1" />
	</body>
</html>