You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 17独立组件中Hammer.js垂直滑动失效问题求解

Angular 17中Hammer.js垂直滑动不触发的解决方法

1. 确认DIRECTION_ALL正确导入

你的HammerConfig中使用了DIRECTION_ALL,但必须确保从hammerjs库导入该常量——否则会被视为未定义,Hammer会默认仅识别水平方向滑动:

import { DIRECTION_ALL } from 'hammerjs';

@Injectable()
export class HammerConfig {
  overrides: any = {
    swipe: { direction: DIRECTION_ALL },
  };
}

2. 调整Swipe识别阈值

Hammer.js默认的滑动触发阈值对垂直滑动不够友好,可降低阈值和速度要求,让垂直滑动更容易被检测:

@Injectable()
export class HammerConfig {
  overrides: any = {
    swipe: { 
      direction: DIRECTION_ALL,
      threshold: 20,   // 触发滑动的最小距离(单位:px)
      velocity: 0.2    // 触发滑动的最小速度(单位:px/ms)
    },
  };
}

3. 确保滑动元素有足够交互区域

检查.test元素的CSS,保证它有足够的高度供垂直滑动触发,同时禁用浏览器默认触摸行为避免事件冲突:

.test {
  height: 100vh;
  width: 100%;
  border: 1px solid #ccc;
  touch-action: none; /* 阻止浏览器拦截触摸事件,让Hammer优先处理 */
}

4. 直接用Hammer实例调试(可选)

如果以上步骤无效,可以绕开Angular封装,直接初始化Hammer实例排查问题:

import { ElementRef, OnInit } from '@angular/core';
import Hammer from 'hammerjs';

export class SwipeComponent implements OnInit {
  swipeEvent = '';

  constructor(private el: ElementRef) {}

  ngOnInit() {
    const hammer = new Hammer(this.el.nativeElement);
    hammer.get('swipe').set({ direction: Hammer.DIRECTION_ALL });
    hammer.on('swipeup swipedown swipeleft swiperight', (ev) => {
      console.log('Hammer直接检测到手势:', ev.type);
      this.startAnimation(ev.type);
    });
  }

  startAnimation(state: string) {
    this.swipeEvent = state;
    console.log('startAnimation', state);
  }
}

内容的提问来源于stack exchange,提问作者Baptiste MARTY

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 17:33:24