[英]$(window).scroll() firing on page load
有沒有辦法防止$(window).scroll()
在頁面加載時觸發?
在Firefox 4中測試以下代碼,即使拔下鼠標,它也會觸發。
jQuery(document).ready(function($){
$(window).scroll(function(){
console.log("Scroll Fired");
});
});
scroll
事件與鼠標無關,只要設置了新的文檔滾動位置,就將調用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提供了跨瀏覽器的替代方案。
這就是我追求的解決方案。 任何改進都將不勝感激。
var scroll = 0;
$(window).scroll(function(){
if (scroll>0){
console.log("Scroll Fired");
}
scroll++;
});
僅在刷新滾動的頁面時或直接導航到錨點時,滾動事件不會在每次加載時觸發。
許多答案建議在首次調用時忽略它,如果頁面一開始沒有滾動,則將忽略有效的滾動。
//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>
這似乎對我有用。
$(window).bind("load", function() {
$(window).on("scroll", function () {
console.log('scroll');
});
});
當然,在加載之后才加載它。 讓它回撥500毫秒的睡眠時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.