使用
new TouchMoveDirection({
el: document.querySelector('.perfect-moment'),
onMoveEnd: (result) => {
if (result.direction === 'to-bottom') {
}
}
})
代码
class TouchMoveDirection {
constructor({ el, onMoveEnd, needTouchPosition }) {
this.onMoveEnd = onMoveEnd
this.el = el
this.startX = null
this.startY = null
this.moveEndX = null
this.moveEndY = null
this.X = null
this.Y = null
this.needTouchPosition = needTouchPosition
this.touchPosition = null
this.duration = 0
this.startTime = 0
this.endTime = 0
if (this.needTouchPosition) {
const boundingClientRect = this.el.getBoundingClientRect()
this.boundaryLine = {
pageX: (boundingClientRect.left + boundingClientRect.right) / 2,
pageY: this.el.offsetTop + (boundingClientRect.height / 2)
}
}
this.init()
}
init = () => {
this.el?.addEventListener('touchstart', this.touchstart)
this.el?.addEventListener('touchend', this.touchend)
}
touchstart = (e) => {
e.stopPropagation()
this.startTime = new Date().getTime()
this.startX = e.changedTouches[0].pageX
this.startY = e.changedTouches[0].pageY
if (this.needTouchPosition) {
this.touchPosition = this.getTouchPosition(this.startX, this.startY)
}
}
touchend = (e) => {
e.stopPropagation()
this.endTime = new Date().getTime()
this.duration = this.endTime - this.startTime
if (this.duration < 1000) {
this.moveEndX = e.changedTouches[0].pageX
this.moveEndY = e.changedTouches[0].pageY
this.X = this.moveEndX - this.startX
this.Y = this.moveEndY - this.startY
if (Math.abs(this.X) > Math.abs(this.Y) && this.X > 0 && Math.abs(this.X) > 30) {
this.onMoveEnd?.({
touchPosition: this.touchPosition,
direction: 'to-right'
})
} else if (Math.abs(this.X) > Math.abs(this.Y) && this.X < 0 && Math.abs(this.X) > 30) {
this.onMoveEnd?.({
touchPosition: this.touchPosition,
direction: 'to-left'
})
} else if (Math.abs(this.Y) > Math.abs(this.X) && this.Y > 0 && Math.abs(this.Y) > 30) {
this.onMoveEnd?.({
touchPosition: this.touchPosition,
direction: 'to-bottom'
})
} else if (Math.abs(this.Y) > Math.abs(this.X) && this.Y < 0 && Math.abs(this.Y) > 30) {
this.onMoveEnd?.({
touchPosition: this.touchPosition,
direction: 'to-top'
})
}
}
}
getTouchPosition = (startX, startY) => {
if (startX >= this.boundaryLine.pageX) {
if (startY >= this.boundaryLine.pageY) {
return 'right-bottom'
} else {
return 'right-top'
}
} else {
if (startY >= this.boundaryLine.pageY) {
return 'left-bottom'
} else {
return 'left-top'
}
}
}
off() {
this.el?.removeEventListener('touchstart', this.touchstart)
this.el?.removeEventListener('touchend', this.touchend)
}
}
export default TouchMoveDirection