$(window).scroll() firing on page load

后端 未结 5 617
无人及你
无人及你 2020-12-20 16:01

Is there a way to prevent $(window).scroll() from firing on page load?

Testing the following code in Firefox 4, it fires even when I unplug the mouse.<

5条回答
  •  再見小時候
    2020-12-20 16:08

    The scroll event is unrelated to the mouse, it is called whenever a new document scrolling position is set. And arguably that position is set when the document loads (you might load it with an anchor after all), also if the user presses a cursor key on his keyboard. I don't know why you need to ignore the initial scroll event but I guess that you only want to do it if pageYOffset is zero. That's easy:

    var oldPageYOffset = 0;
    $(window).scroll(function(){
      if (window.pageYOffset != oldPageYOffset)
      {
        oldPageYOffset = window.pageYOffset;
        console.log("Window scrolling changed");
      }
    });
    

    Note: MSIE doesn't have window.pageYOffset property so the above will need to be adjusted. Maybe jQuery offers a cross-browser alternative.

提交回复
热议问题