我认为您应该采用基于模型的方法(特别适合角度),即当您向上滚动并达到限制时,您会加载更多数据并将它们插入到消息集合的开头(如果您也可以删除最新的出于性能原因,您想限制加载的 html 节点的数量)。
这是我用lrInfiniteScroll使用的那种方法
根本没有 dom 操作,它只是检测您何时向下滚动并到达底部(使用去抖动)并触发您绑定的处理程序,因此您可以做任何您想做的事情,特别是更改您的模型:您的应用程序仍然是模型驱动的
我已经稍微改变了逻辑以具有向上滚动的行为,但想法保持不变
(function (ng) {
'use strict';
var module = ng.module('lrInfiniteScroll', []);
module.directive('lrInfiniteScroll', ['$timeout', function (timeout) {
return{
link: function (scope, element, attr) {
var
lengthThreshold = attr.scrollThreshold || 50,
timeThreshold = attr.timeThreshold || 400,
handler = scope.$eval(attr.lrInfiniteScroll),
promise = null,
lastScrolled = -9999;
lengthThreshold = parseInt(lengthThreshold, 10);
timeThreshold = parseInt(timeThreshold, 10);
if (!handler || !ng.isFunction(handler)) {
handler = ng.noop;
}
element.bind('scroll', function () {
var scrolled = element[0].scrollTop;
//if we have reached the threshold and we scroll up
if (scrolled < lengthThreshold && (scrolled - lastScrolled) < 0) {
//if there is already a timer running which has no expired yet we have to cancel it and restart the timer
if (promise !== null) {
timeout.cancel(promise);
}
promise = timeout(function () {
handler();
//scroll a bit againg
element[0].scrollTop=element[0].clientHeight/2;
promise = null;
}, timeThreshold);
}
lastScrolled = scrolled;
});
//scroll first to the bottom (with a delay so the elements are rendered)
timeout(function(){
element[0].scrollTop=element[0].clientHeight;
},0);
}
};
}]);
})(angular);
和一个正在运行的例子