[removed] How to detect if browser window is scrolled to bottom?

后端 未结 19 1014
你的背包
你的背包 2020-11-22 16:00

I need to detect if a user is scrolled to the bottom of a page. If they are at the bottom of the page, when I add new content to the bottom, I will automatically scroll them

19条回答
  •  太阳男子
    2020-11-22 16:22

    I was searching for an answer but haven't found an exact one. Here is a pure javascript solution that works with latest Firefox, IE and Chrome at the time of this answer:

    // document.body.scrollTop alone should do the job but that actually works only in case of Chrome.
    // With IE and Firefox it also works sometimes (seemingly with very simple pages where you have
    // only a 
     or something like that) but I don't know when. This hack seems to work always.
    var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
    
    // Grodriguez's fix for scrollHeight:
    // accounting for cases where html/body are set to height:100%
    var scrollHeight = (document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight;
    
    // >= is needed because if the horizontal scrollbar is visible then window.innerHeight includes
    // it and in that case the left side of the equation is somewhat greater.
    var scrolledToBottom = (scrollTop + window.innerHeight) >= scrollHeight;
    
    // As a bonus: how to scroll to the bottom programmatically by keeping the horizontal scrollpos:
    // Since window.innerHeight includes the height of the horizontal scrollbar when it is visible
    // the correct vertical scrollTop would be
    // scrollHeight-window.innerHeight+sizeof(horizontal_scrollbar)
    // Since we don't know the visibility/size of the horizontal scrollbar
    // we scroll to scrollHeight that exceeds the value of the
    // desired scrollTop but it seems to scroll to the bottom with all browsers
    // without problems even when the horizontal scrollbar is visible.
    var scrollLeft = (document.documentElement && document.documentElement.scrollLeft) || document.body.scrollLeft;
    window.scrollTo(scrollLeft, scrollHeight);
    

提交回复
热议问题