【发布时间】:2014-06-12 01:16:14
【问题描述】:
我有一个简单的 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());
};
这按预期工作,如果窗口高度为 500 像素,文档高度为 1000 像素,则初始滚动位置为 50%。如果你滚动到底部,它将是 100%。
我想做的是让我的初始值为 1%,当滚动到底部时它返回 100%(就像现在一样)。
问题是我的初始值 50% 是基于窗口高度(显示一半页面)。由于某种原因,我无法计算出从 1% 开始并在达到底部时达到 100% 的必要数学运算。
【问题讨论】:
-
您要解决的实际问题是什么,想要 1% 而不是 0% 的原因是什么?
-
@Nit 这不是问题所在。如果您阅读问题,OP 不希望初始高度考虑页面的当前位置。因此,对于 1000 像素的文档高度和 500 像素的窗口高度,而不是初始窗口 % 为 50 OP 希望它为 1%。虽然我确信 OP 不会在意它是 0% 而不是 1%
-
@Nit - 我认为 1% 只是滚动时在页面上发生视觉效果的一个很好的偏移量。不过,如果它从 0% 开始,我可能会实现我正在寻找的东西。谢谢
-
@adjit - 你是对的。
标签: javascript html math height