你們都知道jQuery裏沒有touch事件,因此在移動端使用原生js實現上拉加載效果仍是很不錯的,閒話很少說,代碼以下:css
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請求數據的方法,在這裏不在贅述簡單的實現了基本功能,須要的話能夠在這個基礎上實現更多功能歡迎你們批評指正~~