Get scroll position and direction with vanilla JS

2019-07-12 02:54发布

问题:

I'm trying to complete a project without using jQuery. Looking good until now. But, there is something I can't manage: scroll position and direction.

What I basically want is to add a class to an element when we reach a point when going down and remove that class when we reach the same point, but, going up.

回答1:

I have created a JSFiddle recently it might help you to get this done. http://jsfiddle.net/UFV7R/5/ You have to include the detection from where you are scrolling, you could do this by storing the last scrollbar position and compare it to the current one.



回答2:

You are going to want to use

var scrollObject = {};
window.onscroll = getScrollPosition;

function getScrollPosition(){
    scrollObject = {
       x: window.pageXOffset,
       y: window.pageYOffset
    }
    // If you want to check distance
    if(scrollObject.y > 200) {
        // add class
    } else {
        // remove class
    }
}

That said, I would highly recommend looking into a throttling method to improve performance of this method.