Get scroll position and direction with vanilla JS

2019-07-12 02:36发布

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.

2条回答
老娘就宠你
2楼-- · 2019-07-12 03:05

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.

查看更多
祖国的老花朵
3楼-- · 2019-07-12 03:24

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.

查看更多
登录 后发表回答