我有一个简单的 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);
}
这是 fiddle :http://jsfiddle.net/XNVNj/2/
只要看看你的控制台。应该解释一切。
关于Javascript 滚动高度百分比数学,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24167891/