[英]How to hit a function when scroll position is reaches the top position?
When scroll position hit the top position of the document the function is called.当滚动位置到达文档的顶部位置时,该函数被调用。 How to do that?
怎么做?
Good way to do it is to use the HostListener这样做的好方法是使用 HostListener
@HostListener("window:scroll", [])
onWindowScroll() {
let scroll = this.window.pageYOffset || this.document.documentElement.scrollTop || this.document.body.scrollTop || 0;
if (number = 0) {
// Do some stuff here
}
}
Now I just wanna add that you probably need to account for elastic scroll on mac desktops.现在我只想补充一点,您可能需要考虑 mac 桌面上的弹性滚动。 Meaning that your scroll position can go in minus, and might not hit 0 exactly when you want this event to fire.
这意味着您的滚动位置可以为负,并且在您希望触发此事件时可能不会准确地达到 0。
Here is a good blog post about this, if you want more reading material如果您想要更多阅读材料,这里有一篇关于此的好博客文章
Use addEventListener on body, and listen for 'scroll' event, then when event is fired check scrollY property of window, and if it is 0, then you are on top.在 body 上使用 addEventListener,并监听 'scroll' 事件,然后当事件被触发时检查窗口的 scrollY 属性,如果它是 0,那么你就在上面。
function yourFunction() {
console.log('you are on top');
}
window.addEventListener('scroll', () => {
if (window.scrollY == 0) yourFunction();
}, true);
You can use HostListener to listen to the scroll event您可以使用 HostListener 来监听滚动事件
@HostListener("window:scroll", ["$event"])
onWindowScroll() {
// get scroll postion
let number = this.window.pageYOffset ||
this.document.documentElement.scrollTop || this.document.body.scrollTop ||
0;
// here you can check the scroll postion
if (number > 100) {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.