Javascript滚动高度百分比数学

Javascript Scroll Height Percentage Math

本文关键字:百分比 高度 滚动 Javascript      更新时间:2023-09-26

我有一个简单的JS模块,计算当前滚动位置的百分比。

var scrollPercent = (function() {
    "use strict";
    var module = {
        config: {
        },
        init: function() {
            return this.percent();
        },
        percent: function() {
            var windowHeight = this.getWindowHeight();
            var docHeight = this.getDocHeight();
            var scrollPosition = this.getScrollPosition();
            var result = ((scrollPosition + windowHeight) / docHeight) * 100;
            return Math.floor(result);
        },
        getScrollPosition: function() {
            return (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;               
        },
        getWindowHeight: function() {
            return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0;
        },
        getDocHeight: function() {
            return Math.max(
                document.body.scrollHeight || 0, 
                document.documentElement.scrollHeight || 0,
                document.body.offsetHeight || 0, 
                document.documentElement.offsetHeight || 0,
                document.body.clientHeight || 0, 
                document.documentElement.clientHeight || 0
            );                
        }
    };
    return module;
});
var scroller = new scrollPercent;
window.onscroll = function(event) {
    console.log(scroller.init());
};

这是预期的工作,如果窗口高度为500px,文档高度为1000px,那么初始滚动位置为50%。如果你要滚动到底部,它将是100%。

我想做的是让我的初始值为1%,当滚动到底部时,它返回100%(就像现在一样)。

问题是,我的初始值50%是基于窗口高度(显示的页面的一半)。出于某种原因,我无法计算出必要的数学方法,让它从1%开始,到达底部时达到100%。

所以,经过一番折腾,我找到了你的解决方案…

您必须考虑文档和滚动条的当前位置。所以如果你想让它在0-100之间,你必须排除docHeight中窗口的高度。

在您的函数中,我创建了一个名为initDiff的变量,并基本上使用它来计算0-100之间的值。

这就是我如何设置你的init函数。注意docHeight。另外,请注意initDiff,它计算需要从结果中减去的差异。我没有使用任何滚动条定位因为initDiff是在滚动条定位为0

时计算的
init: function() {
    var windowHeight = this.getWindowHeight();
    var docHeight = this.getDocHeight() - windowHeight;
    initDiff = (windowHeight / docHeight) * 100;
    console.log('Difference : ' + initDiff);
    return this.percent();
}

下面是你的百分比函数,我改变了一点。同样,docHeight考虑了窗口的当前高度。你的结果是,一旦你从docHeight中取出windowHeight你的数字通常在50-150之间,这都取决于窗口的高度。我所做的是"保留"这个数字,但我会计算这个差值。所以对于这个范围,你的initDiff将是50。如果范围是56-156你的initDiff将是56

percent: function() {
    var windowHeight = this.getWindowHeight();
    var docHeight = this.getDocHeight() - windowHeight;
    var scrollPosition = this.getScrollPosition();            
    var result = ((scrollPosition + windowHeight) / docHeight) * 100 - initDiff;
    console.log('Window Height : ' + windowHeight);
    console.log('Document Height : ' + docHeight);
    console.log('Scroll Position : ' + scrollPosition);
    return Math.floor(result);
}

这是小提琴:http://jsfiddle.net/XNVNj/2/

看看你的控制台。