您的位置:首页 > Web前端 > AngularJS

使用Angularjs、jQuery在手机上实现滑动条到底自动加载更多功能

2016-04-28 14:16 946 查看
关键词:directive infiniteScroll infiniteScrollDistance infiniteScrollDisabled $window.on $window.off

在网上查了很多相关技术,在电脑浏览器上能正常的实现自动加载更多功能,但是放到手机APP壳子上就不行了。下面把代码和自己的分析写下来,便于以后回忆。

首先使用angularjs里的指令来使任何用到自动加载更多的地方都可以调用到这个方法:

app.directive('infiniteScroll', [
'$rootScope', '$window', '$timeout', function($rootScope, $window, $timeout) {
return {
link: function(scope, elem, attrs) {
//里面加入下面的代码
}
};
}
]);


自动加载更多的主要思路是当滑动条滚动到底部时,会触发原有的手动ng-click="function()"函数,达到加载更多目的。

所以我们要获取三个很关键的数值:

1.当前选中元素页面的总长度elem.children().height()。

2.滑动条向下滑动的距离$window.scrollTop()。

3.所选中元素展示框的高度$window.height()。

当2+3=1时,就可以触发加载更多函数了,从而达到目的。

为了实时获取最新的上面三个值,我使用jQuery的$window.on('scroll', handler);方法,将滑动条scroll动作和handler函数绑定起来,在handler函数中判断当前2+3是不是等于1了,等于时则执行getmore();

代码如下:

var checkWhenEnabled, handler, scrollDistance, scrollEnabled;
$window = angular.element(elem);
scrollDistance = 0;
if (attrs.infiniteScrollDistance != null) {//接收并返回触发加载更多的距离
scope.$watch(attrs.infiniteScrollDistance, function(value) {
return scrollDistance = parseInt(value, 10);
});
}
scrollEnabled = true;
checkWhenEnabled = false;
if (attrs.infiniteScrollDisabled != null) {
scope.$watch(attrs.infiniteScrollDisabled, function(value) {
scrollEnabled = !value;
if (scrollEnabled && checkWhenEnabled) {
checkWhenEnabled = false;
return handler();
}
});
}
handler = function() {
var elementBottom, remaining, shouldScroll, windowBottom;
windowBottom = $window.height() + $window.scrollTop();
elementBottom = elem.children().height();
remaining = elementBottom - windowBottom;
shouldScroll = remaining <=  scrollDistance;
if (shouldScroll && scrollEnabled) {//达到可加载距离
console.log("$rootScope.$$phase",$rootScope.$$phase);
if ($rootScope.$$phase) {
return scope.$eval(attrs.infiniteScroll);//执行getmore操作
} else {
return scope.$apply(attrs.infiniteScroll);//执行getmore操作
}
} else if (shouldScroll) {
return checkWhenEnabled = true;
}
};
$window.on('scroll', handler);//监控scroll滑动则运行handler函数
scope.$on('$destroy', function() {//离开页面则关闭scroll与handler的绑定
return $window.off('scroll', handler);
});
以上就是directive中的代码,接下来在html中要监控的dom元素顶端加入以下代码:

<div infinite-scroll="getMore()" infinite-scroll-disabled='busy' infinite-scroll-distance='1'>
之后再js代码中写加载更多getmore()函数:

$scope.getMore=function(){
$scope.custParam.page=$scope.custParam.page+1;//加载页数+1
}
html和js中的代码要根据实际情具体问题具体分析,directive中的代码一般是可以通用的。

效果图如下:





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息