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

11
有没有办法防止$(window).scroll()在页面加载时触发?在Firefox 4中测试以下代码,即使我拔掉鼠标,它仍会触发。
jQuery(document).ready(function($){    
$(window).scroll(function(){
                console.log("Scroll Fired");
    });
});

你需要禁止滚动的任何示例是什么? - genesis
我只需要在没有滚动发生时阻止滚动事件的触发。 - Mild Fuzz
2
小心将任何东西挂钩到窗口滚动事件上 http://ejohn.org/blog/learning-from-twitter/ - redsquare
5个回答

13

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提供的跨浏览器解决方案。


这几乎完成了,我只需要防止第一次运行! - Mild Fuzz
4
@Mild Fuzz:如果你解释想要实现什么而不是如何实现它,你将得到更好的答案。你认为忽略第一个滚动事件是最好的解决方案,但这可能并非如此(如果没有更多信息,就无法确定)。无论如何,如果你绝对想要忽略初始的“scroll”事件,也可以使用window.pageYOffset来初始化oldPageYOffset - Wladimir Palant

9
这是我采取的解决方案。如有改进意见,非常感激。
   var scroll = 0;
    $(window).scroll(function(){
                    if (scroll>0){
                    console.log("Scroll Fired");
                    }
                    scroll++;
    });

3
这对我来说似乎有效。
$(window).bind("load", function() {
    $(window).on("scroll", function () {
        console.log('scroll');
    });
});

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>


0

当然,加载之后再加载它。将其设置为500毫秒睡眠的回调函数。


以上代码是在 jQuery(document).ready(function($){ 中加载的,它不是。 - Mild Fuzz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接