Vue项目中添加手势实现左滑右滑操作
Vue项目中添加手势实现左滑右滑操作
-
左滑右滑等手势可通过监听
touchstart
和touchmove
事件实现 -
touchstart
记录起始坐标 -
touchmove
计算当前位置 -
加上绝对值判断更加精确。
-
<div id="rightSwip">右滑关闭</div>
data() {
return {
startX: 0,
startY: 0
}
},
mounted() {
document.getElementById('rightSwip').addEventListener('touchstart', function(e) {
// console.log('touchstart:', e)
e.preventDefault()
this.startX = e.changedTouches[0].pageX
this.startY = e.changedTouches[0].pageY
})
document.getElementById('rightSwip').addEventListener('touchmove', function(e) {
// console.log('touchmove:', e)
e.preventDefault()
if (e.changedTouches.length) {
let moveEndX = e.changedTouches[0].pageX
let moveEndY = e.changedTouches[0].pageY
let X = moveEndX - this.startX
let Y = moveEndY - this.startY
if (Math.abs(X) > Math.abs(Y) && X > 0) {
console.log("left 2 right", X, Y);
} else if (Math.abs(X) > Math.abs(Y) && X < 0) {
console.log("right 2 left", X, Y);
} else if (Math.abs(Y) > Math.abs(X) && Y > 0) {
console.log("top 2 bottom", X, Y);
} else if (Math.abs(Y) > Math.abs(X) && Y < 0) {
console.log("bottom 2 top", X, Y);
} else {
console.log("just touch", X, Y);
}
}
})
},
本文来自博客园,作者:struggle_time,转载请注明原文链接:https://www.cnblogs.com/songliquan/p/12784634.html