How do I know the IntersectionObserver scroll direction?

后端 未结 5 2042
半阙折子戏
半阙折子戏 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:21

    Comparing boundingClientRect and rootBounds from entry, you can easily know if the target is above or below the viewport.

    During callback(), you check isAbove/isBelow then, at the end, you store it into wasAbove/wasBelow. Next time, if the target comes in viewport (for example), you can check if it was above or below. So you know if it comes from top or bottom.

    You can try something like this:

    var wasAbove = false;
    
    function callback(entries, observer) {
        entries.forEach(entry => {
            const isAbove = entry.boundingClientRect.y < entry.rootBounds.y;
    
            if (entry.isIntersecting) {
                if (wasAbove) {
                    // Comes from top
                }
            }
    
            wasAbove = isAbove;
        });
    }
    

    Hope this helps.

提交回复
热议问题