【问题标题】:How to fire only once Mousewheel scroll如何只触发一次鼠标滚轮滚动
【发布时间】:2019-10-21 12:25:15
【问题描述】:

我正在尝试使用鼠标滚轮滚动来执行一些操作。我希望无论您滚动滚轮多快或多少次,它都算作“一个”。现在,如果您快速滚动,它将计算更多次。

https://stackblitz.com/edit/angular-yttk3y

【问题讨论】:

标签: javascript angular events scroll mousewheel


【解决方案1】:

有一个计时器来限制滚动一段时间并保持滚动方向以检测滚动方向的变化。

import { Directive, HostListener } from '@angular/core';
import { timer } from 'rxjs';
@Directive({
  selector: '[appMouseScroll]'
})
export class MouseScrollDirective {
  Ttimer;
  isMouseWheelInRogress;
  scrollUp;

  @HostListener('wheel', ['$event']) onMouseScroll(e) {

    if (!this.isMouseWheelInRogress || (!this.scrollUp && e.deltaY < 0 || this.scrollUp && e.deltaY > 0)) {
      if (this.Ttimer) {
        this.Ttimer.unsubscribe();
      }
      this.Ttimer = timer(500).subscribe(() => {
        this.isMouseWheelInRogress = false;
      });

      if (e.deltaY < 0) {
        this.scrollUp = true;
        console.log('scrolling up');
      } else if (e.deltaY > 0) {
        this.scrollUp = false;
        console.log('scrolling down');
      }
    }
    this.isMouseWheelInRogress = true;
  }
}

【讨论】:

    【解决方案2】:

    保存滚动方向并在条件类似的情况下使用它

    scrollDirection:'up'|'down';
       @HostListener('wheel', ['$event']) onMouseScroll(e) {
        if (e.deltaY < 0 && this.scrollDirection !='up') {
          console.log('scrolling up');
          this.scrollDirection='up';
        } else if (e.deltaY > 0 && this.scrollDirection !='down') {
          console.log('scrolling down');
          this.scrollDirection='down';
        }
      }
    

    demo

    【讨论】:

      【解决方案3】:

      你需要有一个超时功能,以避免所有的滚动事件,只触发最后一个事件。

      这里是例子。 https://angular-pwnp9p.stackblitz.io

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-14
        • 1970-01-01
        • 2012-11-26
        • 1970-01-01
        相关资源
        最近更新 更多