$(window).scroll()在页面加载时触发

时间:2011-06-23 10:59:47

标签: javascript jquery events javascript-events scroll

有没有办法阻止$(window).scroll()在页面加载时触发?

在Firefox 4中测试以下代码,即使拔下鼠标,它也会触发。

jQuery(document).ready(function($){    
$(window).scroll(function(){
                console.log("Scroll Fired");
    });
});

5 个答案:

答案 0 :(得分:10)

scroll事件与鼠标无关,只要设置了新的文档滚动位置,就会调用它。并且可以说,当文档加载时设置位置(你可以用一个锚加载它),如果用户按下键盘上的光标键也是如此。我不知道为什么你需要忽略最初的scroll事件,但我想如果pageYOffset为零,你只想这样做。这很简单:

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

注意:MSIE没有window.pageYOffset属性,因此需要调整上述内容。也许jQuery提供了跨浏览器的替代方案。

答案 1 :(得分:7)

这是我的解决方案。感激地收到了任何改进。

   var scroll = 0;
    $(window).scroll(function(){
                    if (scroll>0){
                    console.log("Scroll Fired");
                    }
                    scroll++;
    });

答案 2 :(得分:3)

滚动事件不会在每次加载时触发,只有在刷新滚动的页面或直接导航到锚点时才会触发。

许多答案建议忽略第一次调用它,如果页面最初没有滚动,则忽略有效滚动。

//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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
</div>

答案 3 :(得分:0)

当然,请不要在加载之后加载它。让它成为500毫安的睡眠回电。

答案 4 :(得分:0)

这似乎对我有用。

$(window).bind("load", function() {
    $(window).on("scroll", function () {
        console.log('scroll');
    });
});