说多了都是泪,在进行项目开发时,在上拉加载更多实现分页效果的问题上,由于当时开发任务紧急,所以就百度找了各种移动端的上拉下拉
实现加载更多的插件。然后就留下了个坑:上拉加载的时候会由于用户错误的姿势,例如长按后再touchmove等会出现卡死的假象。(ps:当然,
我不认为是插件的问题,当时的想法是觉得引用的插件存在冲突),于是,我就直接通过封装touch事件完成上拉加载实现分页的功能。
备注:文章最后会加上为实现这个功能我找的一些插件
在应用touch事件实现上拉加载更多实现分页的效果上,其实我们用到的只有touchstart,touchmove,touchend,touchcancel事件,还有targetTouches[0]
和changedTouches[0]属性即可完成简单的分页效果。
了解更多touch事件的方法可以访问:
https://developer.mozilla.org/zh-CN/docs/web/API/Touch
在执行touch事件的时候,在大多数情况下我们需要注意的就是阻止浏览器的默认行为,例如滚动事件或者浏览器的缩放,可以通过html页面加上meta标签禁止
用户缩放:<meta name="viewport" content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">,然后
在touch事件上加上event.preventDefault()阻止默认事件。
通过基于zepto简单的封装了touch事件上拉加载更多的效果。
- ;(function ($,window,undefined) {
- var userDefinedSlide={
- isSupportTouch:"ontouchstart" in document ? true :false,
- startPos:{},//touchstart的位置信息
- endPos:{},//touchmove的位置信息
- upOrDown:'',//up:为上拉加载,down为下拉刷新
- winHigh:0,//浏览器的高度,
- docHigh:0,//文档的高度,对应于页面总高度
- scrollHigh:0,//滚动的高度
- notDefault:false,//是否阻止默认行为
- //docHigh=winHigh+scrollHigh
- init:function(){
- if(!this.isSupportTouch){
- console.warn('touch events are not supported at current device');
- }else{
- this.touchEvents();
- }
- },
- touchEvents:function(){
- var that=this;
- $("body").on("touchstart",function (e) {
- var touch=e.targetTouches[0];
- that.startPos={
- x:touch.pageX,
- y:touch.pageY,
- time:+new Date()
- };
- that.winHigh=$(window).height();//可视窗口高度
- that.docHigh=$(document).height();//总高度
- that.scrollHigh=$(window).scrollTop();//滚动高度
- });
- $("body").on("touchmove",function (e) {
- if(that.notDefault){
- e.preventDefault();
- }
- var touch=e.targetTouches[0];
- that.endPos={
- x:touch.pageX,
- y:touch.pageY,
- time:+new Date()
- };
- that.upOrDown=that.endPos.y-that.startPos.y;
- });
- $("body").on("touchend touchcancel",function (e) {
- if(that.upOrDown < 0 && that.docHigh<=(that.winHigh+that.scrollHigh)){
- console.log('is to bottom');
- //可执行动画效果
- setTimeout(function(){
- //需要异步加载数据放置位置
- //若执行动画,则加载数据后移除动画效果
- },1000);
- }
- })
- }
- };
- userDefinedSlide.init();
- })( Zepto ,window,undefined);
而基于是在touchmove事件执行获取触摸位置还在touchend/touchcancel事件执行获取触摸位置则我没有过多的考究。
要在touchend/touchcancel事件获取触摸位置的话则需要将var touch=e.targetTouches[0];调整为var touch=e.changedTouches[0];
因为,touchend/touchcancel事件没有targetTouches属性,只有changedTouches属性。
可能有人存在疑惑,为啥要绑定touchend和touchcancel两个事件呢,个人事件,发现在部分安卓手机上会在touchend事件上有bug,不能
执行,所以通过执行touchcancel事件:当系统停止跟踪触摸的时候触发,来达到touchend的效果。
通过我上面对touch事件的简单封装就可实现上拉加载更多实现分页的效果了。
dropload:https://github.com/ximan/dropload
iScroll:https://github.com/cubiq/iscroll
swiper:https://github.com/nolimits4web/Swiper(ps:swiper也可实现上拉加载更多)
mescroll:http://www.mescroll.com/
另:我文章开头提到的使用插件存在的bug,有知道的大神可以留言给我喔,再次谢过先了。
来源: http://www.cnblogs.com/aaron-pan/p/7459589.html