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

22 篇文章 0 订阅
12 篇文章 0 订阅

关键词: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中的代码一般是可以通用的。

效果图如下:









  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值