我的个人网站:https://m.theeye.tech/
之前有分享过一次原生js实现上拉加载,今天我来给大家分享下原生js实现下拉刷新;等后面有时间我将把这两个放一起封装成一个简单的方法,我个人认为会比mescroll的包小,且较为方便,而且我认为mescroll的兼容问题还是很多的。
好了,废话不多说,开始正题:
实现下拉刷新原理主要是利用移动端的touch事件来实现的;
touch事件主要为以下几种:
touchstart : 触摸开始(手指放在触摸屏上)
touchmove : 拖动(手指在触摸屏上移动)
touchend : 触摸结束(手指从触摸屏上移开)
touchenter :移动的手指进入一个dom元素。
touchleave :移动的手指离开一个dom元素。
还有一个touchcancel,是在拖动中断时候触发。
而我们下拉刷新的过程主要是用到了触碰屏幕(touchstart),开始下拉(touchmove),松手(touchend)。
对的,原理就是这么简单,但是实际上处理下拉还是有挺多的小问题的,先上代码:
js代码
// 下拉刷新 _this.outerScroller.addEventListener( 'touchstart', function (event) { var touch = event.targetTouches[0]; // 把元素放在手指所在的位置 _this.touchStart = touch.pageY; // event.preventDefault(); // 阻止浏览器默认下滑事件 }, false ); _this.outerScroller.addEventListener( 'touchmove', function (event) { var touch = event.targetTouches[0]; _this.scroll.style.top = _this.scroll.offsetTop + touch.pageY - _this.touchStart + 'px'; _this.touchStart = touch.pageY; _this.touchDis = touch.pageY - _this.touchStart; if (_this.scroll.offsetTop > 0 && document.body.scrollTop < 50) { document.body.addEventListener('touchmove', _this.preEvent, { passive: false }); // passive 参数不能省略,用来兼容ios和android _this.emptyDiv.style.marginTop = Number(_this.scroll.style.top.replace(/\s+|px/gi, '')) + 20 + 'px'; // 让下拉的父级高度等于下滑部分+下滑距离,让整体呈现下拉的感觉 } else { return; } if (_this.scroll.offsetTop >= 80) { // 限制下拉的距离 _this.scroll.style.top = '80px'; } }, false ); _this.outerScroller.addEventListener( 'touchend', function (event) { _this.touchStart = 0; var top = _this.scroll.offsetTop; var num = _this.scroll.style.top.replace(/\s+|px/gi, ''); // 将top值转成数值 if (num < 0) { // 当上滑到顶部的时候,不超过边界 _this.scroll.style.top = '0px'; return; } if (top > 40) refresh(); if (top > 0) { var time = setInterval(function () { _this.scroll.style.top = _this.scroll.offsetTop - 2 + 'px'; _this.emptyDiv.style.marginTop = Number(_this.scroll.style.top.replace(/\s+|px/gi, '') + 20) + 'px'; // 让下拉的父级高度等于下滑部分+下滑距离,让整体呈现下拉的感觉 if (_this.scroll.offsetTop <= 0) clearInterval(time); }, 1); } /* var time = setTimeout(function(){ scroll.style.top = scroll.offsetTop -2+'px'; emptyDiv.style.height = Number(360) + Number(scroll.style.top.replace(/\s+|px/gi,"")) + 'px'; // 让下拉的父级高度等于下滑部分+下滑距离,让整体呈现下拉的感觉 if(scroll.offsetTop<=0)clearTimeout(time); time(); },1) while(top>0){ time(); } */ // event.stopPropagation(); // window.event.returnValue = false; document.body.removeEventListener('touchmove', _this.preEvent, { passive: false }); // passive 参数不能省略,用来兼容ios和android }, false ); function refresh () { console.log('下拉刷新'); }
html和css文件不知道扔哪里去了,到时候再补补吧,先这样啦,工作~