【问题标题】:Get scroll percentage in a dom container [duplicate]获取dom容器中的滚动百分比[重复]
【发布时间】:2014-05-17 01:11:26
【问题描述】:

我有一个应用程序,其内容应在用户向下滚动时加载(如 Twitter/Facebook...)。

我正在尝试根据滚动事件和当前滚动位置检测何时加载更多数据。

我读过这篇文章:https://stackoverflow.com/a/3898152/82609

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

这几乎可以工作,但在我的情况下,当我滚动到底部时,我有

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

窗口滚动顶部+窗口高度怎么可能大于高度? 不是很大,只是一点点。

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 

很多时候,当我完全滚动到底部时,我会得到一些不知从何而来的额外像素。有人可以解释一下吗?


我正在尝试计算容器中滚动内容的百分比:

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

这个函数工作得很好,除了当我滚动到底部时,我经常到达103% -> 对我的用例来说没什么大不了的,但我正在努力理解这个问题。

【问题讨论】:

    标签: javascript jquery scroll pagination scrolltop


    【解决方案1】:

    尝试使用$(document).outerHeight() 而不是$(document).height()

    FIDDLE WORKING

    【讨论】:

    • 我刚刚添加了一个 Fiddle 来演示它的工作原理;)
    • 谢谢,但实际上它似乎不是问题。如您所见,这个简单的小提琴不会重现我的问题,因为当您滚动到底部时,它会打印 100% 而不是 103%:jsfiddle.net/pR3ET/1
    • 这里打印 100% 呵呵,你用的是什么浏览器?我在这里使用的是 Chrome(SS:img.ctrlv.in/img/14/04/04/533ef5cd8cd43.png),我在做这个例子时使用的是 Firefox。
    • 顺便说一句,你有没有尝试用我的解决方案更新你的网站,看看这是否不起作用?这个东西“来自无处的额外像素”通常用于您应该使用的那些外部高度。如果这不适合您的问题,请使用您的 HTML 更新您的问题,以便我可以在这里重现您的问题。
    猜你喜欢
    • 2015-04-24
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-18
    • 2018-12-24
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多