demo.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>Document</title>
<style>
html,body {
height: 100%;
}
.box {
height: 80px;
width: 80px;
border: 1px solid #000;
background-color: red;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
window.onload = function() {
var box = document.querySelector(".box");
var startX = 0; // 手指开始滑动的位置
var startY = 0;
var distanceX = 0; // 手指总共滑动的距离(滑动距离的叠加)
var distanceY = 0;
var moveX = 0; // 手指滑动的距离
var moveY = 0;
document.body.addEventListener("touchstart",function(event) {
startX = event.touches[0].clientX;
startY = event.touches[0].clientY;
});
document.body.addEventListener("touchmove",function(event) {
moveX = event.touches[0].clientX - startX;
moveY = event.touches[0].clientY - startY;
box.style.transform = "translate("+ (distanceX+moveX) +"px,"+(distanceY+moveY)+"px)"; // 根据移动距离进行偏移
});
document.body.addEventListener("touchend",function(event) {
distanceX = distanceX + moveX; // 记录/更新手指总共滑动的距离
distanceY = distanceY + moveY;
});
}
</script>
</body>
</html>