简体   繁体   English

当滚动位置到达顶部位置时如何点击功能?

[英]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.

相关问题 当滚动位置到达屏幕中的元素位置时如何显示和转换? - How to display and transition when scroll position reaches element position in the screen? 当滚动位置到达底部时,如何在数组中推送项目? - How to push item in array when scroll position reaches to bottom? 滚动条上固定的位置在到达顶部之前开始(顶部div) - Position fixed on scroll starts before it reaches the top (top div) 当内部元素滚动 position 到达顶部/底部时防止父元素滚动? - Prevent scrolling of parent element when inner element scroll position reaches top/bottom? 当位置从滚动窗口顶部到达85px时修复div - Fix div when position reaches 85px from top of window on scroll addEventListener(“scroll”) 加载时如何不调度且初始滚动 position 不在顶部 - How not to dispatch addEventListener(“scroll”) when it is loaded and the initial scroll position is not at the top 当用户滚动位置到达位置时将javascript加载到div中 - Load javascript into div when user scroll position reaches it 修复滚动时的位置元素,并在到达父级的末尾时删除 - Fix position element on scroll and remove when reaches the end of parent 将dom添加到顶部时如何保持滚动位置 - How can I keep scroll position when add dom to top 将项目添加到 div 顶部时,如何保持在同一个滚动 position 中? - How to stay in same scroll position when adding items to the top of a div?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM