Get scroll percentage in a dom container

孤者浪人 提交于 2019-12-08 08:39:04

问题


I have an app with content that should be loaded when the user scrolls down (like Twitter/Facebook...).

I'm trying to detect when to load more data based on scroll events and the current scroll position.

I've read this post: https://stackoverflow.com/a/3898152/82609

if($(window).scrollTop() + $(window).height() == $(document).height()) {
    console.error("bottom!");
}

This nearly works but in my case when I scroll to the bottom I have

$(window).scrollTop() + $(window).height() > $(document).height()

How is it possible that window scrolltop + window height is greater than height? It is not so much greater, just a little bit.

console.error("$(window).scrollTop() + $(window).height()=",$(window).scrollTop() + $(window).height(),"  VS  $(document).height()",$(document).height());

// It gives me in the console:
$(window).scrollTop() + $(window).height()= 877   VS  $(document).height() 872 

Very often, when I have scrolled totally to the bottom I get some extra pixels that comes from nowhere. Can someone explain this?


I'm trying to compute the percentage of scrolled content in a container:

    getScrollPercentage: function(scrollableElementSelector) {

        var scrollableElement = $(scrollableElementSelector);

        // This is the number of hidden pixels of the scrollable element inside its container
        var hiddenHeigth;
        if ( scrollableElementSelector === window ) {
            hiddenHeigth = $(document).height() - $(window).height();
        } else {
            hiddenHeigth = scrollableElement[0].scrollHeight - scrollableElement.outerHeight();
        }

        // This is the number of scrolled pixels
        var scrolledHeight = scrollableElement.scrollTop();

        if ( hiddenHeigth < scrolledHeight ) {
            //throw new Error("hiddenHeigth "+hiddenHeigth+" < scrolledHeight " +scrolledHeight + " -> Impossible unless you didn't use this function correctly");
        }

        var scrollPercent = ( scrolledHeight / hiddenHeigth ) * 100;

        if ( this.debug ) {
            console.debug("hiddenHeigth=",hiddenHeigth,"scrolledHeight=",scrolledHeight,"scrollPercent=",scrollPercent);
        }

        return scrollPercent;
    }

This function works pretty well, except when I scroll to the bottom, I often get up to 103% -> Not a big deal for my usecase but I'm trying to understand the problem.


回答1:


Try to use $(document).outerHeight() instead of $(document).height()

FIDDLE WORKING



来源:https://stackoverflow.com/questions/22867584/get-scroll-percentage-in-a-dom-container

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!