$(window).scroll()在页面加载时触发 [英] $(window).scroll() firing on page load
问题描述
有没有办法防止在页面加载时触发$ code> $(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
事件与鼠标无关,只要设置了新的文档滚动位置,就会调用它。并且可以说,当文档加载时,您的位置将被设置(您可以使用锚点加载该位置),如果用户按下键盘上的光标键也是如此。我不知道为什么你需要忽略最初的滚动
事件,但是我猜想如果 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没有窗口.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屋!