angular - 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");
}
解决方案
在 Angular DOM Manipulation 中,您不应该使用 java 脚本。角度框架主要是为以角度方式操作 dom 而创建的。
window.addEventListener('scroll', this.scroll, true);
不是以角度监听事件的方式
您可以使用 window:scroll 来检测滚动事件。我创建了自定义指令来处理滚动检查这个例子 https://stackblitz.com/edit/bottom-ovzmcq
推荐阅读
- java - 使用 JDBC 将数据插入数据库的问题
- nuget - Azure Pipelines NuGet.config 包无法还原
- python - Xgboost 与简单的时间序列数据框 Python
- javascript - Javascript 执行代码块
- r - 加载 RCurl 包失败
- javascript - 为什么即使在 .on 委托方法之后进行 DOM 更改时 JQuery 也不起作用
- windows - 为什么多播套接字在具有两个网络接口的系统上按预期工作?
- git - Webhook 和 CI/CD 之间的区别
- sockets - 不知道端口号的套接字连接 - Python
- angular - IONIC 4 中的 Cloud Firestore 功能