检查页面是否在窗口的顶部

check if the page is on the top of the window

本文关键字:窗口 顶部 是否 检查      更新时间:2023-09-26

我需要检查一个html页面是否在窗口的顶部。

所以,我使用这个代码:

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

但是这并没有像预期的那样工作,因为事件应该只有在用户停止滚动动作时才被触发。任何想法?

试试这个:

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

使用setTimeout:

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