2013-05-30 29 views
0

我需要檢查一個html頁面是否在窗口的頂部。檢查頁面是否在窗口頂部

所以,我使用此代碼:

$(window).scroll(function(){ 
    a = ($(window).scrollTop()); 
    if (a>0) { 
     alert('page not in top'); 
    } 
}); 

但如預期,因爲該事件應該只在用戶停止滾動操作被解僱,這是行不通的。任何想法?

回答

1

試試這個:

var timer = null; 
$(window).addEventListener('scroll', function() { 
    if(timer !== null) { 
     clearTimeout(timer);   
    } 
    timer = setTimeout(function() { 
      // do something 
    }, 150); 
}, false); 

或者這一個:

var timer; 
    $(window).bind('scroll',function() { 
     clearTimeout(timer); 
     timer = setTimeout(refresh , 150); 
    }); 
    var refresh = function() { 
     // do stuff 
     console.log('Stopped Scrolling'); 
    }; 
+0

感謝。第一個代碼中的「addEventListener不是函數」。無論如何,第二個完美的作品。 – anvd

1

使用setTimeout

var timeout; 

$(window).scroll(function() { 
    clearTimeout(timeout); 
    timeout = setTimeout(function(){ 
     a = $(window).scrollTop(); 
     if (a > 0) { 
      alert('page not in top'); 
     } 
    }, 100); 
});