【发布时间】:2014-05-17 01:11:26
【问题描述】:
我有一个应用程序,其内容应在用户向下滚动时加载(如 Twitter/Facebook...)。
我正在尝试根据滚动事件和当前滚动位置检测何时加载更多数据。
我读过这篇文章:https://stackoverflow.com/a/3898152/82609
if($(window).scrollTop() + $(window).height() == $(document).height()) {
console.error("bottom!");
}
这几乎可以工作,但在我的情况下,当我滚动到底部时,我有
$(window).scrollTop() + $(window).height() > $(document).height()
窗口滚动顶部+窗口高度怎么可能大于高度? 不是很大,只是一点点。
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
很多时候,当我完全滚动到底部时,我会得到一些不知从何而来的额外像素。有人可以解释一下吗?
我正在尝试计算容器中滚动内容的百分比:
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% -> 对我的用例来说没什么大不了的,但我正在努力理解这个问题。
【问题讨论】:
标签: javascript jquery scroll pagination scrolltop