移动端实现移动小方块

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title></title>

		<style type="text/css">
			*{
				margin: 0;padding: 0;
			}
			
			
			.box1 {
				width: 200px;
				height: 200px;
				background-color: #f00;
				text-align: center;
				line-height: 200px;
				font-size: 30px;
				
				position: absolute;
			}
			
			
		</style>

	</head>
	<body>
		<div class="box1">
			box1
		</div>
		<script type="text/javascript">
			var box1 = document.querySelector('.box1');
			var div_html=document.querySelector("html")
			// 起始值
			var ori_pos;
			// 【移动端事件】
			div_html.ontouchstart=function(e){
				console.log('触摸屏幕 ')
				ori_pos=[e.touches[0].clientX,e.touches[0].clientY];
				console.log('起始:',ori_pos)
			}
			div_html.ontouchmove=function(e){
				// 计算变化量
				temp_x= e.touches[0].clientX -ori_pos[0];
				temp_y= e.touches[0].clientY -ori_pos[1];
				// 位置移动
				box1.style.marginLeft = parseInt(getComputedStyle(box1).marginLeft)+temp_x+'px';
				box1.style.marginTop = parseInt(getComputedStyle(box1).marginTop)+temp_y+'px';
				// 更新初始值
				ori_pos=[e.touches[0].clientX,e.touches[0].clientY];
			}
			div_html.ontouchend=function(e){
				console.log('离开屏幕',e)
			}
		</script>

	</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_40994735/article/details/108024240