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

后端 未结 19 945
你的背包
你的背包 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

    window.onscroll = function(ev) {
        if ((window.innerHeight + Math.ceil(window.pageYOffset)) >= document.body.offsetHeight) {
            alert("you're at the bottom of the page");
        }
    };
    

    This Answer will fix edge cases, this is because pageYOffset is double while innerHeight and offsetHeight are long, so when the browser gives you the info, you may be a pixel short. For example: on bottom of the page we have

    true window.innerHeight = 10.2

    true window.pageYOffset = 5.4

    true document.body.offsetHeight = 15.6

    Our calculation then becomes: 10 + 5.4 >= 16 which is false

    To fix this we can do Math.ceil on the pageYOffset value.

    Hope that helps.

提交回复
热议问题