如何实现自定义手势识别?请实现一个滑动手势检测
解读
国内前端面试中,手势识别是“移动端体验优化”高频考点。面试官并非只想看“能跑”的代码,而是考察:
- 对 Touch 事件模型(touchstart/touchmove/touchend)与浏览器默认行为(滚动、缩放)的理解;
- 能否用原生 API 完成“起点-终点”向量计算、速度估算、方向判定;
- 代码是否可复用、可扩展(后续加 pinch、rotate 能否低成本接入);
- 性能与内存意识:事件监听器及时解绑、避免高频 move 回调导致掉帧;
- 兼容性:iOS 13+ 需要 passive:false 才能 e.preventDefault(),部分安卓需兼顾 pointer 事件降级。
题目限定“滑动手势”,只需识别“左/右/上/下”单次滑动,但要求“自定义”,意味着不能依赖第三方库,必须手写可配置策略(最小滑动距离、最大允许停顿时间、速度阈值)。
知识点
- TouchEvent 与 Touch 对象:touches/targetTouches/changedTouches 区别
- 向量运算:Δx、Δy、距离、角度、速度
- 方向判定:Math.atan2 + 45° 分象限
- 防抖与节流:move 事件 16 ms 触发一次,需节流避免计算浪费
- passive 事件监听器:preventDefault() 与滚动冲突
- 内存泄漏:组件卸载时移除监听器
- 可扩展架构:策略模式(阈值配置)、状态机(start→move→end/cancel)
- 兼容性:pointermove 降级、iOS 双击缩放穿透处理
答案
以下代码为“零依赖、可配置、可销毁”的滑动手势识别器,符合国内主流浏览器与 WebView(微信、钉钉、手百)环境。
/**
* SwipeGesture 类
* 支持四方向 swipe 识别,可配置阈值与回调
* 使用方式:
* const swipe = new SwipeGesture(element, {
* minDistance: 30, // px
* maxDuration: 300, // ms
* minVelocity: 0.3, // px/ms
* onSwipe: ({ direction, distance, duration, velocity }) => {}
* });
* swipe.enable(); // 开启
* swipe.disable(); // 关闭并释放监听
*/
class SwipeGesture {
constructor(el, options = {}) {
this.el = el;
this.minDistance = options.minDistance || 30;
this.maxDuration = options.maxDuration || 300;
this.minVelocity = options.minVelocity || 0.3;
this.onSwipe = options.onSwipe || (() => {});
this.startX = 0;
this.startY = 0;
this.startTime = 0;
this._onStart = this._onStart.bind(this);
this._onMove = this._throttle(this._onMove.bind(this), 16);
this._onEnd = this._onEnd.bind(this);
this._onCancel = this._onEnd; // touchcancel 与 touchend 等价处理
}
enable() {
// 必须 passive:false 才能禁止默认滚动,避免 swipe 与页面滚动冲突
const opts = { passive: false, capture: false };
this.el.addEventListener('touchstart', this._onStart, opts);
this.el.addEventListener('touchmove', this._onMove, opts);
this.el.addEventListener('touchend', this._onEnd, opts);
this.el.addEventListener('touchcancel', this._onCancel, opts);
}
disable() {
const opts = { passive: false, capture: false };
this.el.removeEventListener('touchstart', this._onStart, opts);
this.el.removeEventListener('touchmove', this._onMove, opts);
this.el.removeEventListener('touchend', this._onEnd, opts);
this.el.removeEventListener('touchcancel', this._onCancel, opts);
}
_onStart(e) {
if (e.touches.length !== 1) return; // 单指操作
const t = e.touches[0];
this.startX = t.pageX;
this.startY = t.pageY;
this.startTime = Date.now();
}
_onMove(e) {
// 节流后已保证 60 fps 内最多一次计算,这里可空实现或做实时反馈
}
_onEnd(e) {
const touch = e.changedTouches[0];
const dx = touch.pageX - this.startX;
const dy = touch.pageY - this.startY;
const distance = Math.hypot(dx, dy);
const duration = Date.now() - this.startTime;
const velocity = distance / duration;
if (
distance < this.minDistance ||
duration > this.maxDuration ||
velocity < this.minVelocity
) return;
const angle = Math.atan2(dy, dx) * 180 / Math.PI; // -180 ~ 180
let direction;
if (angle >= -45 && angle < 45) direction = 'right';
else if (angle >= 45 && angle < 135) direction = 'down';
else if (angle >= -135 && angle < -45) direction = 'up';
else direction = 'left';
this.onSwipe({ direction, distance, duration, velocity });
}
_throttle(fn, wait) {
let last = 0;
return function (...args) {
const now = Date.now();
if (now - last >= wait) {
last = now;
fn.apply(this, args);
}
};
}
}
// 使用示例
const box = document.getElementById('slider');
const swipe = new SwipeGesture(box, {
minDistance: 40,
maxDuration: 250,
onSwipe: ({ direction }) => {
console.log('Swipe:', direction);
// 业务:左滑删除、右滑返回、上滑加载更多
}
});
swipe.enable();
要点说明
- 单指过滤:touches.length===1,防止多指误触。
- 向量角度分四象限,45° 为界,保证方向唯一。
- 速度阈值过滤“慢拖”场景,提升准确率。
- 提供 disable(),SPA 切页时销毁,防止内存泄漏。
- passive:false 保证 e.preventDefault() 生效,避免 iOS 13+ 滚动穿透。
拓展思考
- 多点手势:在 _onStart 记录 touch.identifier,维护 Map<id, Point> 可实现 pinch/rotate;需矩阵计算缩放比与旋转角。
- 指针事件降级:统一 pointerdown/pointermove/pointerup,支持鼠标与触控笔,减少分支判断;注意 setPointerCapture 解决移出元素丢失问题。
- 机器学习方案:对于复杂轨迹(字母、签名),可在前端采集序列点,使用 TensorFlow.js 训练轻量级 LSTM/CNN 模型,实现自定义字符识别,避开传统规则阈值难调问题。
- 性能优化:move 阶段仅记录原始点数组,end 阶段统一计算,避免高频开方;WebWorker 可做离线计算,但序列化成本需权衡。
- 无障碍:为滑动手势提供同等键盘/点击操作,避免仅依赖手势导致障碍用户无法使用,符合国内《无障碍信息技术要求》监管趋势。