移动端实现方块拖拽功能

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
	<style type="text/css">
		*{
			margin:0;
			padding:0;
		}
		body{
			height:1000px;
			background:rgb(255, 199, 201);
			position:relative;
		}
		#aEle{
			position:absolute;
			left:50px;
			top:100px;
			width:200px;
			height:200px;
			background:red;
		}
	</style>
</head>
<body>
	<div id="aEle"></div>
	<script type="text/javascript">
		var aEleId = document.querySelector("#aEle");

		var touchFore = {
				x : 0,
				y : 0
			},//前一次触摸位置坐标
			touchNext = {
				x : 0,
				y : 0
			},//下一次触摸位置坐标
			translatePosition = {
				x : 0,
				y : 0
			};

		var myDeviceWidth = document.documentElement.getBoundingClientRect().width || window.innerWidth,//获取设备宽度

			//获取元素高度宽度
			bodyHeight = document.body.offsetHeight,
			aEleWidth = aEleId.offsetWidth,
			aEleHeight = aEleId.offsetHeight,

			//获取元素初始位置,注意:当用translate移动后,offsetLeft/Top属性并不会改变
			aEleX = aEleId.offsetLeft,
			aEleY = aEleId.offsetTop,

			//允许移动的范围
			permitMove = {
				minX : -aEleX,
				maxX : myDeviceWidth - aEleWidth - aEleX,
				minY : -aEleY,
				maxY : bodyHeight - aEleHeight - aEleY
			};

		//拖拽函数
		function drag(option,permitDrag){
			if(permitDrag === true){
				option.style.transform = "translate3d("+translatePosition.x +"px,"+translatePosition.y+"px,0)";
			}else{
				console.log("该元素不允许拖拽");
			}
		}


		aEleId.addEventListener("touchstart",function(e){
			touchFore.x = e.changedTouches[0].pageX;
			touchFore.y = e.changedTouches[0].pageY;
		},false);

		aEleId.addEventListener("touchmove",function(e){
			e.preventDefault();//阻止默认行为
			touchNext.x = e.changedTouches[0].pageX;
			touchNext.y = e.changedTouches[0].pageY;
				translatePosition.x += touchNext.x - touchFore.x;
				translatePosition.x = translatePosition.x > permitMove.minX ? translatePosition.x : permitMove.minX;
				translatePosition.x = translatePosition.x < permitMove.maxX ? translatePosition.x : permitMove.maxX;
				translatePosition.y += touchNext.y - touchFore.y;
				translatePosition.y = translatePosition.y > permitMove.minY ? translatePosition.y : permitMove.minY;
				translatePosition.y = translatePosition.y < permitMove.maxY ? translatePosition.y : permitMove.maxY;
				touchFore.x = touchNext.x;
				touchFore.y = touchNext.y;
				drag(this,true);
		},false);

	</script>
</body>
</html>


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值