javascript 使用 vanilla JS 获取滚动位置和方向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23205622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get scroll position and direction with vanilla JS
提问by Axiol
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.
我试图在不使用 jQuery 的情况下完成一个项目。直到现在看起来还不错。但是,有一些我无法管理:滚动位置和方向。
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.
我基本上想要的是当我们到达一个点时向一个元素添加一个类,当我们到达同一点时删除该类,但是,向上。
回答by Smi Lee
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.
我JSFiddle
最近创建了一个它可能会帮助您完成这项工作。http://jsfiddle.net/UFV7R/5/您必须包括从您滚动的位置进行检测,您可以通过存储最后一个滚动条位置并将其与当前位置进行比较来实现。
回答by Ken Wheeler
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.
也就是说,我强烈建议研究一种限制方法来提高这种方法的性能。