-
在
touchstart
事件中记录下手指触摸的位置startY
。 -
在
touchmove
事件中记录下手指移动的位置moveY
。 -
在
touchend
事件中比较startY
和moveY
的大小,如果moveY
比startY
大,则用户是在向上滑动,反之则是向下滑动。
let startY = 0;
// 监听touchstart事件
function handleTouchStart(e) {
startY = e.touches[0].clientY;
}
// 监听touchmove事件
function handleTouchMove(e) {
const moveY = e.touches[0].clientY;
const direction = moveY > startY ? 'up' : 'down';
console.log(`用户正在向${direction}滑动`);
}
// 监听touchend事件
function handleTouchEnd(e) {
const moveY = e.changedTouches[0].clientY;
const direction = moveY > startY ? 'up' : 'down';
console.log(`用户向${direction}滑动结束`);
}
// 绑定事件
const element = document.querySelector('.scrollable-element');
element.addEventListener('touchstart', handleTouchStart);
element.addEventListener('touchmove', handleTouchMove);
element.addEventListener('touchend', handleTouchEnd);