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

后端 未结 5 621
无人及你
无人及你 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:21

    The scroll event does not fire on every load, only when refreshing a page that was scrolled, or when navigating to an anchor directly.

    Many of the answers suggest ignore the first time it's called, which would ignore a valid scroll if the page doesn't get scrolled initially.

    //Scroll the page and then reload just the iframe (right click, reload frame)
    
    
    //Timeout of 1 was not reliable, 10 seemed to be where I tested it, but again, this is not very elegant.
    //This will not fire initially
    setTimeout(function(){
      $(window).scroll(function(){
         console.log('delayed scroll handler');
      }); 
    }, 10); 
    
    //This will fire initially when reloading the page and re-establishing the scroll position
    $(window).scroll(function(){
      console.log('regular scroll handler');
    });
    div {  
      height: 2000px;
      border: 1px solid red;
    }
    
    

提交回复
热议问题