前言:移动端避不开touch事件,左滑、右滑、下滑、上滑,卡片切换翻页,左滑删除,操作长按遮.......
| touchstart | touchmove | touchend |
|---|---|---|
| 触摸开始,多点触控 | 滑动时 | 滑动结束,手指离开屏幕 |
| touchcancel:触摸被取消,当前系统停止跟踪触摸 | ||
| 备注:除了touchcancel,都包含在touches数组里面 |
touch对象包含的属性
clientX:视口中的触摸目标的X的坐标。
clientY:视口中的触摸目标的Y的坐标。
identifier:标识触摸的唯一ID。
pageX:页面中的触摸目标的X的坐标。
pageY:页面中的触摸目标的Y的坐标。
screenX:屏幕中的触摸目标的X的坐标。
screenX:屏幕中的触摸目标的Y的坐标。
target:触摸的DOM节点的目标。
举个栗子-----------------------------------------------------
touchStart: function (e) {
this.flag = 1;
this.touchStartX = e.touches[0].pageX;
this.touchStartY = e.touches[0].pageY;
// 使用js计时器记录时间
this.interval = setInterval(function () {
this.time++;
}, 100);
},
touchMove: function (e) {
this.flag = 0;
this.touchMoveX = e.touches[0].pageX;
this.touchMoveY = e.touches[0].pageY;
},
touchEnd: function (e) {
let moveX = this.touchMoveX - this.touchStartX
let moveY = this.touchMoveY - this.touchStartY
if (Math.sign(moveX) == -1) {
moveX = moveX * -1
}
if (Math.sign(moveY) == -1) {
moveY = moveY * -1
}
if (moveX <= moveY && this.flag == 0) {
if (this.touchMoveY - this.touchStartY <= -30 && this.time < 10) {
// 向上
}
if (this.touchMoveY - this.touchStartY >= 30 && this.time < 10) {
// 向下
}
}
if (moveY <= moveX && this.flag == 0) {
if (this.touchMoveX - this.touchStartX <= -30 && this.time < 10) {
// 向左
}
if (this.touchMoveX - this.touchStartX >= 30 && this.time < 10) {
// 向右
}
}
clearInterval(this.interval); // 清除setInterval
this.time = 0;
},
原理理解
坐标系,x轴,y轴 moveX <= moveY 表示X轴方向移动的距离小于Y轴方向移动的距离,手势是在上下移动,同理,手势是在左右移动。
scroll 左右联动
listScroll(event){
if (this.listHeight.length == 0) {
return;
}
let scrollTop = event.detail.scrollTop;
let current = this.data.currentLeftSelected;
if (scrollTop >= this.distance) {
if (current + 1 < this.listHeight.length && scrollTop >= this.listHeight[current]) {
this.currentLeftSelected = current + 1
}
} else {
if (current - 1 >= 0 && scrollTop < this.listHeight[current - 1]) {
this.currentLeftSelected = current - 1
}
}
//更新到顶部的距离
this.distance = scrollTop;
},