问题
I've made a nav on my site which is absolute positioned.
I've made a class to make this fixed to the top of the screen.
What I'm trying to find out is how to carry out a function (toggleClass in this instance) after the windows has been scrolled x amount of pixels down the page (500 px in this instance)
回答1:
The procedure is:
- Listen to the scroll event to detect the user's scroll position as they scroll
- Calculate the element's position from the top of the page, or determine fixed distance from the top of the page (500px, in your example)
- When the scroll position is greater than the trigger position, execute the function. If you only want the function to fire once, remove the scroll listener in the function.
Assuming jQuery, something like this:
$(window).on('scroll', function() {
scrollPosition = $(this).scrollTop();
if (scrollPosition >= 500) {
// If the function is only supposed to fire once
$(this).off('scroll');
// Other function stuff here...
}
});
回答2:
$(window).scroll(function() {
if ($(this).scrollTop() >= 500) {
//custom code
}
});
回答3:
maybe something like:
$(window).scroll(function() { // bind an eventhandler, if user scrolls
if(window.scrollY > 500) { // get amount of pixels - verticalScroll and check whether its higher 500
/* ...*/
}
});
来源:https://stackoverflow.com/questions/21442424/jquery-carry-out-function-after-scroll-past-x-pixels