首页 > 解决方案 > Angular 5窗口滚动事件触发了几次

问题描述

我注意到在我的 Angular 项目中,当我尝试侦听窗口滚动事件时,我的函数在滚动操作结束时每次滚动执行 1 次。最多我的函数被调用两次:滚动开始时和滚动结束时。

如果您查看我使用 Jquery 的这个 plunker,它会为单个滚动操作记录超过 10 次:

$(window).scroll(function() {
    console.log($(this).scrollTop());

});

https://plnkr.co/edit/z3Ajg1fg05OXKRkHMca0?p=preview

现在的问题是我试图重现我所遇到的错误,但我不能。事实上,如果你看一下这个用 angular 制作的小提琴,它就像 jquery 一样工作。 https://jsfiddle.net/1hk7knwq/6592/

我的代码是一样的:

constructor() {
window.onscroll = (s) => {
        console.log(window.pageYOffset);
    };
}

在我的项目中,每个滚动动作只记录 1 或 2 次。你知道为什么会这样吗?请帮忙

我已经尝试了所有其他方法,例如:

window.addEventListener('scroll', this.scroll, true);

或者:

@HostListener('window:scroll', ['$event']) 
    scrollHandler(event) {
      console.debug("Scroll Event");
    }

标签: angulareventsscrollwindow

解决方案


在 Angular DOM Manipulation 中,您不应该使用 java 脚本。角度框架主要是为以角度方式操作 dom 而创建的。

window.addEventListener('scroll', this.scroll, true);不是以角度监听事件的方式

您可以使用 window:scroll 来检测滚动事件。我创建了自定义指令来处理滚动检查这个例子 https://stackblitz.com/edit/bottom-ovzmcq


推荐阅读