一、移动端块的移动
二、移动端方向锁定
一、移动端块的移动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
.box{
width: 200px;
height: 200px;
background-color: #ccc;
transform: translate(0,0);
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var x = 0,y = 0
var oBox = document.querySelector(".box")
oBox.addEventListener("touchstart",function(e){
console.log([oBox])
var disX = e.targetTouches[0].clientX - x;
var disY = e.targetTouches[0].clientY - y;
function fnMove(e){
x = e.targetTouches[0].clientX - disX
y = e.targetTouches[0].clientY - disY
oBox.style.transform = `translate(${x}px,${y}px)`
}
oBox.addEventListener("touchmove",fnMove)
function fnEnd(){
oBox.removeEventListener("touchmove",fnMove)
oBox.removeEventListener("touchend",fnEnd)
}
oBox.addEventListener("touchend",fnEnd)
})
</script>
</body>
</html>
二、移动端方向锁定
当沿着X轴移动的时候,Y轴不能移动,沿着Y轴移动的时候,X轴不能移动,也就是只能沿着一个方向进行移动。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 200px;
height: 200px;
background-color: #ccc;
transform: translate(0, 0);
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var x = 0, y = 0
var oBox = document.querySelector(".box")
oBox.addEventListener("touchstart", function (e) {
var disX = e.targetTouches[0].clientX - x,
disY = e.targetTouches[0].clientY - y,
startX = e.targetTouches[0].clientX,
startY = e.targetTouches[0].clientY,
dir = "" //声明一个变量,这个变量用来记录方向
function fnMove(e) {
if (dir == "") {
// 在这里判断方向
if (Math.abs(e.targetTouches[0].clientX - startX) > 5) {
dir = "x"
} else if (Math.abs(e.targetTouches[0].clientY - startY) > 5) {
dir = "y"
}
} else {
if (dir == "x") {
x = e.targetTouches[0].clientX - disX
} else if (dir == "y") {
y = e.targetTouches[0].clientY - disY
}
oBox.style.transform = `translate(${x}px,${y}px)`
}
}
function fnEnd() {
oBox.removeEventListener("touchmove", fnMove)
oBox.removeEventListener("touchend", fnEnd)
}
oBox.addEventListener("touchmove", fnMove)
oBox.addEventListener("touchend", fnEnd)
})
</script>
</body>
</html>