为什么Scroll Percentage超过100

时间:2017-04-24 20:07:30

标签: javascript scroll

我正在使用此方法计算滚动百分比(在线阅读大量帖子后)。但是,当我滚动到最底部时,滚动百分比转到> 100%。值为:

滚动值:ScrollHeight:3405 scrollBarHeight:1408 scrollTop:1997.3333740234375 scrollPercentage:100.01669374178455

我想明白为什么会发生这种情况,如果我的做法错了?

感谢。

    // This is the container with the scrolbar. We are using this element as we want the inner div. document.documentElement is the full element
    const scrollingElement: HTMLElement = document.getElementById(personalInsightsContainerId);

    // If no scrollingElement is present, do not do anything.
    if (scrollingElement) {
        // The Element.scrollTop property gets or sets the number of pixels that the content of an element is scrolled upward.
        // An element's scrollTop is a form of distance measurement regarding an element's top to its topmost visible content.
        // When an element content does not generate a vertical Scrollbar, then its scrollTop value defaults to 0.
        const scrollTop: number = scrollingElement.scrollTop;

        // The difference b/w scrolling point.
        const scrollingDifference: number = scrollTop - this.lastScrollNumber;

        // We want to scroll if: a) there is scrollElement defined b) either the scrolling is first time or the scrollDifference is > 100.
        if (this.lastScrollNumber === 0 || scrollingDifference > 100) {
            // The Element.scrollHeight read-only property is a measurement of the height of an element's content,
            // Including content not visible on the screen due to overflow.
            const scrollHeight = scrollingElement.scrollHeight;

            // The HTMLElement.offsetHeight read-only property is the height of the element including vertical padding and borders, as an integer.
            const scrollBarHeight = scrollingElement.offsetHeight;

            if (scrollHeight && scrollBarHeight) {
                this.lastScrollNumber = scrollTop;

                 const totalHeight = scrollHeight - scrollBarHeight;
                 const scrollPercentage = totalHeight > 0 ? (scrollTop / totalHeight) * 100 : -1;
        }
    }

2 个答案:

答案 0 :(得分:0)

尝试使用clientHeight而不是offsetHeight

答案 1 :(得分:0)

你使用什么浏览器?在chrome / FF中,Element.scrollTop始终是整数值。尝试使用const scrollTop: number = Math.floor(scrollingElement.scrollTop);