jquery - carry out function after scroll past x pixels [duplicate]

て烟熏妆下的殇ゞ 提交于 2020-07-18 07:25:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!