js实现手势
监听触摸事件
使用touchstart、touchmove和touchend事件来跟踪用户的手势。在事件对象中,可以获取触摸点的坐标信息。
element.addEventListener('touchstart', handleTouchStart);
element.addEventListener('touchmove', handleTouchMove);
element.addEventListener('touchend', handleTouchEnd);
计算手势方向
通过比较起始点和结束点的坐标,可以判断手势的方向。例如,水平滑动可以通过比较x坐标的变化来判断。

let startX, startY;
function handleTouchStart(e) {
startX = e.touches[0].clientX;
startY = e.touches[0].clientY;
}
function handleTouchMove(e) {
const endX = e.touches[0].clientX;
const endY = e.touches[0].clientY;
const diffX = endX - startX;
const diffY = endY - startY;
if (Math.abs(diffX) > Math.abs(diffY)) {
if (diffX > 0) {
console.log('向右滑动');
} else {
console.log('向左滑动');
}
} else {
if (diffY > 0) {
console.log('向下滑动');
} else {
console.log('向上滑动');
}
}
}
实现缩放手势
通过计算两个触摸点之间的距离变化来实现缩放手势。使用touchstart事件记录初始距离,touchmove事件计算当前距离与初始距离的比例。

let initialDistance;
function handleTouchStart(e) {
if (e.touches.length === 2) {
initialDistance = Math.hypot(
e.touches[0].clientX - e.touches[1].clientX,
e.touches[0].clientY - e.touches[1].clientY
);
}
}
function handleTouchMove(e) {
if (e.touches.length === 2) {
const currentDistance = Math.hypot(
e.touches[0].clientX - e.touches[1].clientX,
e.touches[0].clientY - e.touches[1].clientY
);
const scale = currentDistance / initialDistance;
console.log('缩放比例:', scale);
}
}
实现旋转手势
通过计算两个触摸点的角度变化来实现旋转手势。使用Math.atan2函数计算角度差。
let initialAngle;
function handleTouchStart(e) {
if (e.touches.length === 2) {
const dx = e.touches[1].clientX - e.touches[0].clientX;
const dy = e.touches[1].clientY - e.touches[0].clientY;
initialAngle = Math.atan2(dy, dx) * 180 / Math.PI;
}
}
function handleTouchMove(e) {
if (e.touches.length === 2) {
const dx = e.touches[1].clientX - e.touches[0].clientX;
const dy = e.touches[1].clientY - e.touches[0].clientY;
const currentAngle = Math.atan2(dy, dx) * 180 / Math.PI;
const rotation = currentAngle - initialAngle;
console.log('旋转角度:', rotation);
}
}
使用手势库
对于复杂的手势识别,可以使用现成的库如Hammer.js。Hammer.js提供了丰富的手势支持,包括滑动、缩放、旋转等。
const hammer = new Hammer(element);
hammer.on('swipe', function(e) {
console.log('滑动方向:', e.direction);
});
hammer.on('pinch', function(e) {
console.log('缩放比例:', e.scale);
});
hammer.on('rotate', function(e) {
console.log('旋转角度:', e.rotation);
});






