仿iphone通信录滑动时修改固定标题

仿iphone通信录滑动时修改固定标题##

1,效果演示

效果图

2,思路

1, 开始时,去获取到滚动列表中,每一个标题的偏移值,并保存起来

2,监听列表的滚动,以顶部固定的标题为基点,当这个基点在某个列表区域内的时候,那么固定的基点名称就显示所在区域的标题名称

3,代码实现

1,保存滚动列表中每组标题的偏移值

				var list = $('.integral-wrap .list-warp'),

					i = 0,

					// 偏移量,这个值表示,页面布局中,固定的标题和Tab项的高度值
					// 因为下面使用了 offset() 获取每组标题相对于当前视口的偏移量
					OFFSET = 127.421875,

					item;

				// 重置缓存内容
				cache_pois = [];

				for( ; item = list[i++] ; ) {
					var $item = $(item),
						poi = $item.offset().top - OFFSET,
						flg = $item.find('.title-icon').html();

					//保存偏移量的值到缓存中
					cache_pois.push({ poi : poi, flg : flg });
				}

2,监听滚动列表,返回当前基点所在区域的位置和标题名称

			var 
				cache, i = 0,

				poi = {poi : 0, flg : ""},

				// 当前点的位置
				curPoi = cache_pois[0] ? cache_pois[0] : poi,

				// 新的点位置,或则认为是下一个标题的位置
				nextPoi = cache_pois[1] ? cache_pois[1] : poi;

			return function( curLocation ){

				var len = cache_pois.length;
				if( len < 2 || i >= len  ) return curPoi;

				// console.log( curLocation, nextPoi.poi )

				// 当滚动的位置点大于等于当前点的位置并且小于下一个位置点
				// 当基点还在当前区域内
				if( curLocation >= curPoi.poi && curLocation <= nextPoi.poi ){

					return curPoi;

				// 当基点超出当前区域(列表向下滚动)
				} else if( curLocation > nextPoi.poi ) {

					curPoi = nextPoi;
					i++;
					nextPoi = cache_pois[ i + 1 ];

				// 当基点向回滚动的时候
				} else if( curLocation <= curPoi.poi ) {

					nextPoi = curPoi;
					i--;
					curPoi = cache_pois[ i ]
				}

				return curPoi;

			}

3,监听的方法

				if( cache_pois.length <= 0 ) return;

				var top = $(this).scrollTop();

				var title = getCurTitleFn( top );

				// console.log( title.flg , oldTitle)
				if( title.flg !== oldTitle ) {
					$title.html( title.flg );
					oldTitle = title.flg || null;
				}

在此做了优化,不能频繁的修改 DOM 元素的值,使用oldTitle来标记,若新的标题还等于上次保存的标题名,就不做修改。

完整代码下载地址:github下载

posted @ 2016-01-13 09:34  jienyi  阅读(182)  评论(0编辑  收藏  举报