我正在尝试使用鼠标滚轮进行一些操作。我想无论您将轮子滚动多快或多少次,都算作一个。现在,如果您快速滚动,它将计数更多次。
答案 0 :(得分: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;
}
}
答案 1 :(得分:0)
保存滚动方向,并在出现类似情况时使用它
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';
}
}
答案 2 :(得分:0)
您需要在其中具有超时功能,以避免所有滚动事件并仅触发最后一个事件。