$(window).scroll() 在页面加载时触发 [英] $(window).scroll() firing on page load

查看:38
本文介绍了$(window).scroll() 在页面加载时触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

推荐答案

scroll 事件与鼠标无关,每当设置新的文档滚动位置时都会调用它.并且可以说该位置是在文档加载时设置的(毕竟您可能会使用锚点加载它),如果用户按下键盘上的光标键也是如此.我不知道为什么您需要忽略初始 scroll 事件,但我猜您只想在 pageYOffset 为零时才这样做.这很简单:

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");
  }
});

注意:MSIE 没有 window.pageYOffset 属性,所以上面需要调整.也许 jQuery 提供了一种跨浏览器的替代方案.

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

这篇关于$(window).scroll() 在页面加载时触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆