You need to enable JavaScript to run this app. Angular 滑动标记表格单元格功能移动端PointerEvent失效问题
优惠活动
大模型
产品
解决方案
定价
更多

Angular 滑动标记表格单元格功能移动端PointerEvent失效问题

问题产生原因

该问题是移动触摸场景下Pointer事件的默认行为特性导致的,核心原因有两个:

  1. 触摸触发的Pointer事件默认遵循「命中测试锁定」规则:pointerdown 触发后,后续的pointermove、pointerup事件的target会始终绑定到最初触发pointerdown的元素,哪怕指针移出该元素范围,也不会将事件派发给其他经过的元素。
  2. 移动设备触摸滑动时,浏览器默认会触发页面滚动、缩放等系统行为,会主动中断当前正在执行的Pointer事件流,导致后续事件无法触发。
现有实现存在的问题
  • 未调用Pointer事件的setPointerCapture方法将后续指针事件锁定到绑定指令的元素上,导致滑动出初始元素后事件丢失
  • 事件仅绑定在tbody元素上,当指针滑动出tbody范围后,就无法收到pointermove和pointerup事件,容易出现isPainting状态始终为true的异常
  • 直接调用el.click()触发选中逻辑,在移动设备上存在300ms点击延迟,也可能触发其他不必要的绑定行为
  • 未对触摸事件做默认行为拦截,滑动时容易触发页面滚动,打断选择流程
修复方案

修改后的指令代码如下:

import {Directive, ElementRef, EventEmitter, NgZone, Output} from '@angular/core';

@Directive({selector: '[appSwipePaint]'})
export class SwipePaintDirective {
  private isPainting = false;
  private days: HTMLElement[] = [];
  // 新增输出事件,将选中的元素抛给父组件处理,替代直接触发click
  @Output() daySwipeSelected = new EventEmitter<HTMLElement>();

  constructor(private el: ElementRef, private ngZone: NgZone) {
    // 事件绑定到window保证滑出tbody也能收到事件,跑在Angular区域外避免频繁触发变更检测
    ngZone.runOutsideAngular(() => {
      window.addEventListener('pointerdown', (evt: PointerEvent) => this.touchStart(evt));
      window.addEventListener('pointermove', (evt: PointerEvent) => this.touchMove(evt));
      window.addEventListener('pointerup', (evt: PointerEvent) => this.touchEnd(evt));
      window.addEventListener('pointercancel', (evt: PointerEvent) => this.touchEnd(evt));
    })
  }

  touchStart($event: PointerEvent) {
    // 仅处理点击在日历单元格内的事件
    const target = $event.target as HTMLElement;
    if (!target.closest('.day') || !this.el.nativeElement.contains(target)) return;
    $event.preventDefault();
    this.isPainting = true;
    // 锁定指针事件,后续所有事件都会路由到当前元素
    (target as any).setPointerCapture($event.pointerId);
    // 初始选中的元素直接触发
    if (!this.days.includes(target)) {
      this.days.push(target);
      this.daySwipeSelected.emit(target);
    }
  }

  touchMove($event: PointerEvent) {
    if (!this.isPainting) return;
    $event.preventDefault();
    const el = document.elementFromPoint($event.clientX, $event.clientY)?.closest('.day') as HTMLElement;
    if (el && !this.days.includes(el)) {
      this.days.push(el);
      this.daySwipeSelected.emit(el);
    }
  }

  touchEnd($event: PointerEvent) {
    if (!this.isPainting) return;
    const target = $event.target as HTMLElement;
    target.releasePointerCapture?.($event.pointerId);
    this.isPainting = false;
    this.days = [];
  }
}

然后在模板中绑定输出事件即可:

<tbody #body appSwipePaint (daySwipeSelected)="onDaySelected($event)">

在组件中实现onDaySelected方法,替代原来的click事件选中逻辑即可。

内容的提问来源于stack exchange,提问作者Øystein Amundsen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 03:45:04