首页 > 解决方案 > Mouseenter 事件正在跳过元素

问题描述

mouseenter当在元素上触发事件时,我有这个指令来做一些事情。但是当我快速拖动鼠标时,一些元素会在不触发mouseenter事件的情况下被跳过。

我实际上想在鼠标移动时突出显示网格的一系列单元格。我已将此指令添加到网格单元的模板中。

@Directive({
  // tslint:disable-next-line:directive-selector
  selector: '[appRangeSelector]'
})
export class RangeSelectorDirective {

   @Input() public selectorParams: any;

   public isSelected = false;

   constructor(private elRef: ElementRef,
       private renderer: Renderer2) { }

   @HostListener('mouseenter', ['$event']) public onMouseEnter(e) {
       if (e.buttons === 1 || e.buttons === 3) {

           if (!this.isSelected) {
               console.log('selected');
               this.renderer.setStyle(this.elRef.nativeElement, 'background', 'blue');
               this.isSelected = true;
           } else {
               console.log('deselected');
               this.renderer.setStyle(this.elRef.nativeElement, 'background', 'unset');
               this.isSelected = false;
           }

       }
   }

}

当用户以任何速度选择单元格范围时,我需要选择范围。对此的任何帮助表示赞赏。

标签: javascriptangularmouseenter

解决方案


操作系统只在一定的时间间隔更新鼠标位置,不保证连续移动。

如果你想防弹,你可能需要监听 mousemove 事件,计算轨迹,并检查它是否与你的任何元素相交。但是,我担心这可能有点重,所以你最好先对其进行基准测试。


推荐阅读