当前位置: 首页 > Web前端 > HTML5

移动端用下拉刷新的方式实现上拉加载

时间:2023-04-05 20:57:45 HTML5

上拉加载最常见的实现方式是监听滚动条的滚动事件,而移动端的下拉刷新是使用transform属性移动的,所以使用下拉刷新的方式pull-上载?HTML结构

这里我们做了两个主框,实现两个框内的上拉加载。结构非常简单。css样式*{边距:0;填充:0;}.main-box{背景:天蓝色;宽度:100%;高度:300px;溢出:隐藏;}.popup-box{宽度:100%;}.item{宽度:100%;行高:40px;文本对齐:居中;填充:20px;框大小:边框框;}.tips{文本对齐:居中;}#box2{margin-top:50px;最外面的盒子设置了overflow:hidden;中间框高度未设置,由子框项支持。js代码/*下拉加载*/functiontDscroll(obj){this.key=true;//防止重复请求this.dom=obj.dom;//传入domthis.fn=obj.fn;//回调函数this.outDom=this.dom.querySelector(".popup-box");//获取内容框this.showHeight=dom.offsetHeight;//显示高度this.actualHeight=this.outDom.offsetHeight;//获取实际高度的内容this.startY=0;//开始点击位置this.changedY=0;//手指移动的距离this.originY=0;//偏移量varthat=this;this.dom.addEventListener("touchstart",function(ev){that.onStart(ev);});this.dom.addEventListener("touchmove",function(ev){that.onMove(ev);});this.dom.addEventListener("touchend",function(ev){that.onEnd(ev);});这。fn。调用(这个,这个。outDom);};tDscroll.prototype.onStart=function(ev){this.startY=ev.targetTouches[0].clientY;vartempArr=window.getComputedStyle(this.outDom).transform.split(",");if(tempArr.length>2){this.originY=parseInt(tempArr[tempArr.length-1])||0;}};tDscroll.prototype.onMove=function(ev){this.changedY=ev.touches[0].clientY-this.startY;varchangNum=(this.originY+this.changedY);varscrollHeight=-changNum+this.showHeight;如果(changNum>50)返回;如果(滚动高度>this.actualHeight+50)返回;if(scrollHeight>this.actualHeight-50&&this.key){this.fn.call(this,this.outDom);}this.outDom.style.cssText="transform:translateY("+changNum+"px);";};tDscroll.prototype.onEnd=function(){if((this.originY+this.changedY)>50){this.outDom.style.cssText="变换:translateY(0px);transition:all.3s";}if(-(this.originY+this.changedY)+this.showHeight>this.actualHeight+50){this.outDom.style.cssText="transform:translateY(-"+(this.actualHeight-this.showHeight)+“px”;过渡:所有.3s”;}};vardom=document.querySelector("#box1");//获取domvardom2=document.querySelector("#box2");//获取domvarobj={dom:dom,fn:add};varobj2={dom:dom2,fn:添加};新的tDscroll(obj);新的tDscroll(obj2);变种页=0;//当前的页面数(模拟)//模拟ajaxfunctionadd(outDom){varthat=this;this.key=false;变量str="";对于(vari=1;i<11;i++){str+=""+(i+((page)*10))+""}page++;setTimeout(function(){vartips=outDom.querySelector(".tips");//获取推广提示&&outDom.removeChild(tips);//如果不是第一次添加str+="Loadmore";outDom.innerHTML+=str;那.actualHeight=outDom.offsetHeight;那.键=真;},2000)}原理也很简单,监听手势事件判断距离是否够,够了就加数据~~~