While Scrolling: if scrollTop() equals to or reaches a value execute event

自古美人都是妖i 提交于 2020-01-14 05:26:05

问题


I'm trying to fire an event when scrolling down to a certain point/value and execute again when scroll back up and down again.

I tried:

$(window).scroll(function(){
    var sTop = $(this).scrollTop();

    if(sTop == 300){
        //execute event - failed
    }

});

The above does not fire anything with the both mousewheel and dragging the scrollbar. but when I changed the condition to greater than or equal to, the event is being executed but multiple times when scrolling further down.

if(sTop >= 300){
    //execute event - success
}

I also tried changing the condition value and some times the event is being fired.

if(sTop == 333 /* or 431, 658, etc. */){
    //execute event - sometimes success
}

Here is my test fiddle.

Could it be that scroll() function sometimes skips a value if you scroll fast?

Can someone explain the issue and help me with a workaround on how to trigger an event when the $(window).scrollTop() == 'value'. Thanks


回答1:


You're facing this issue because there are no guarantees that scrolling will be done in increments of 1. For example, some scroll wheels increment in values of 30. This means that you'd get a scroll event on 30, 60, 90, etc.

The best way to test if scrolling has reached your limit is to see if it has gone past the point you're wanting, then resetting the scroll to the precise point you're wanting. So you'd do:

if(sTop >= 300){
    $(window).scrollTop(300);
}

Here's an updated link to your JSFiddle with a working example: http://jsfiddle.net/bC3Cu/4/

If you take a look at unit of increment in scrollable areas / divs in javascript? it describes how to set it to where you can override the scroll increment. Using that method, you should be able to predict how many units the user has scrolled without preventing them from scrolling further down the page.



来源:https://stackoverflow.com/questions/20039258/while-scrolling-if-scrolltop-equals-to-or-reaches-a-value-execute-event

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