大家都知道jQuery里没有touch事件,所以在移动端使用原生js实现上拉加载效果还是很不错的,闲话不多说,代码如下:
1 //获取要操作的元素 2 var objSection = document.getElementsByTagName("div")[0]; 3 //给元素绑定监听事件 个人习惯把监听事件写在一块 4 objSection.addEventListener("touchstart", touchStart, false); 5 objSection.addEventListener("touchmove", touchMove, false); 6 objSection.addEventListener("touchend", touchEnd, false); 7 8 //touchStart 触发事件时要执行的方法 9 function touchStart(event) { 10 event.preventDefault(); 11 this.startY = event.changedTouches[0].pageY; 12 } 13 14 //touchMove 触发事件的过程执行的方法 15 function touchMove(event) { 16 var change = event.changedTouches[0].pageY - this.startY; 17 this.change = change; 18 this.parentNode.style["-webkit-transform"] = "translate(0," + this.change + "px)"; 19 this.parentNode.style["transform"] = "translate(0," + this.change + "px)"; 20 this.parentNode.style["-webkit-transition"] = "all " + 0 + "s"; 21 this.parentNode.style["transition"] = "all " + 0 + "s"; 22 } 23 24 //touchEnd 事件结束执行的方法 25 function touchEnd(event) { 26 if (this.change < 0) { 27 this.parentNode.style["-webkit-transform"] = "translate(0," + this.change + "px)"; 28 this.parentNode.style["transform"] = "translate(0," + this.change + "px)"; 29 this.parentNode.style["-webkit-transition"] = "all " + 1 + "s"; 30 this.parentNode.style["transition"] = "all " + 1 + "s"; 31 appendData(this); 32 } else { 33 this.parentNode.style["-webkit-transform"] = "translate(0," + 0 + "px)"; 34 this.parentNode.style["transform"] = "translate(0," + 0 + "px)"; 35 this.parentNode.style["-webkit-transition"] = "all " + 0.5 + "s"; 36 this.parentNode.style["transition"] = "all " + 0.5 + "s"; 37 } 38 }
上拉加载更多需要注意的地方:在触发上拉这个动作时记录下当前页的pageY,在动作结束时记录下在页面中的pageY,结束时的pageY-开始时的pageY得到变化的pageY,在做css3动画时需要用到变化的pageY,touchEnd里面的appendData方法为ajax请求数据的方法,在这里不在赘述
简单的实现了基本功能,需要的话可以在这个基础上实现更多功能
欢迎大家批评指正~~