javascript拖拽盒子移動的實現

原理比較簡單,能夠參照以前的文章javascript淘寶主圖放大鏡功能幫助理解。javascript

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style type="text/css">
			*{
				margin: 0;
				padding: 0;
			}
			#box{
				position: absolute;
				left: 50px;
				top: 50px;
				width: 200px;
				height: 200px;
				background: red;
			}
			#box2{
				position: relative;
				box-sizing: border-box;
				width: 800px;
				height: 400px;
				margin: 50px auto;
				border: 1px solid gray;
			}
			
		</style>
		<script type="text/javascript">
			window.onload = function (){
				var box = document.getElementById('box');
				var box2 = document.getElementById('box2');
				var boxX = 0;
				var boxY = 0;
				box.onmousedown = function (ev){
					var ev = ev||event;
					boxX = ev.clientX - box.offsetLeft;
					boxY = ev.clientY - box.offsetTop;
					
					var n = 10;//吸附參數
					
					if(box.setCapture){
						document.onmousemove = mousemove;
						document.onmouseup = mouseup;
						box.setCapture();//IE中將其餘地方的事件集中到box
						
					}
					else{
						document.onmousemove = mousemove;
						document.onmouseup = mouseup;
					}
					
					
					function mousemove (ev){
						var ev = ev||event;
						var l = ev.clientX - boxX;
						var t = ev.clientY - boxY;
						//邊緣吸附處理
						if(l<n){
							l = 0;
						}
						else if(l>box2.offsetWidth-box.offsetWidth-n){
							l = box2.offsetWidth-box.offsetWidth-2;
						}
						if(t<n){
							t = 0;
						}
						else if(t>box2.offsetHeight-box.offsetHeight-n){
							t = box2.offsetHeight-box.offsetHeight-2;
						}
						box.style.left = l+"px";
						box.style.top = t+"px";
						
						
					}
					function mouseup (){
						this.onmousemove = null;
						this.onmouseup = null;
						if(this.releaseCapture)
						{
							this.releaseCapture();
						}
					}
					return false;
				}
				
			}
		</script>
	</head>
	<body>
		<div id="box2">
			<div id="box"></div>
		</div>
	</body>
</html>
相關文章
相關標籤/搜索