How do I know the IntersectionObserver scroll direction?

后端 未结 5 2044
半阙折子戏
半阙折子戏 2020-12-07 18:48

So, how do I know the scroll direction when the event it\'s triggered?

In the returned object the closest possibility I see is interacting with the boundingCli

5条回答
  •  情书的邮戳
    2020-12-07 19:42

    My requirement was:

    • do nothing on scroll-up
    • on scroll-down, decide if an element started to hide from screen top

    I needed to see a few information provided from IntersectionObserverEntry:

    • intersectionRatio (should be decreasing from 1.0)
    • boundingClientRect.bottom
    • boundingClientRect.height

    So the callback ended up look like:

    intersectionObserver = new IntersectionObserver(function(entries) {
      const entry = entries[0]; // observe one element
      const currentRatio = intersectionRatio;
      const newRatio = entry.intersectionRatio;
      const boundingClientRect = entry.boundingClientRect;
      const scrollingDown = currentRatio !== undefined && 
        newRatio < currentRatio &&
        boundingClientRect.bottom < boundingClientRect.height;
    
      intersectionRatio = newRatio;
    
      if (scrollingDown) {
        // it's scrolling down and observed image started to hide.
        // so do something...
      }
    
      console.log(entry);
    }, { threshold: [0, 0.25, 0.5, 0.75, 1] });
    

    See my post for complete codes.

提交回复
热议问题