<!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>