[英]Get scroll position and direction with vanilla JS
I'm trying to complete a project without using jQuery.我试图在不使用 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.我基本上想要的是当我们到达一个点时向一个元素添加一个类,当我们到达同一点时删除该类,但是,向上。
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.也就是说,我强烈建议研究一种节流方法来提高这种方法的性能。
I have created a JSFiddle
recently it might help you to get this done.我最近创建了一个JSFiddle
它可能会帮助您完成这项工作。 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. http://jsfiddle.net/UFV7R/5/您必须包括从滚动位置进行的检测,您可以通过存储最后一个滚动条位置并将其与当前位置进行比较来实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.