获取dom容器中的滚动百分比 [英] Get scroll percentage in a dom container

查看:111
本文介绍了获取dom容器中的滚动百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我读过这篇文章: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;
    }

此功能运行良好,除非我滚动到底部,我经常得到 103% - >对我的用例来说没什么大不了的,但我正试图理解这个问题。

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.

推荐答案

尝试使用 $(document).outerHeight()代替of $(document).height()

FIDDLE WORKING

FIDDLE WORKING

这篇关于获取dom容器中的滚动百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆