代碼:
//頁面上拉觸底事件的處理函數 onReachBottom(e) { console.log("底部")// 滾動到頁面執行 該 方法 wx.showToast({ title: '加載中...', icon: 'loading', duration: 2000 }) /* 這里執行你需要的請求數據追加到循環數組就好了 */ }, onPageScroll(e) { console.log(e) //滾動條 滾動的位置(e.scrollTop)從頭部開始計算 },
原理:
上拉加載更多這個需求我相信應該應用頗為廣泛的,今天說我認為兩種可行的方式哈 。
一、第一個應該是最簡單的一種實現方式,文檔自帶的一個api 可以監聽滾動到頁面底部的方法(onReachBottom) 、"onPageScroll"方法可以監聽頁面滾動條的位置。(PS:頁面.json 中'onReachBottomDistance:number'默認為50,這個可以設置在距離底部多少px執行onReachBottom方法,具體使用看你需求。)
1.首先准備幾個盒子 使其 超出page 頁面高度產生滾動條、然后准備一個加載動畫具體實現如下:
//wxml: arr是length為4的數組隨意定義 只是為了撐高度的 <view class='warp'> <view wx:for="{{arr}}" class='bg_cl'></view> </view> <!--加載動畫 --> <view class='bottom'> <view class="loading"> <text></text> <text></text> <text></text> <text></text> <text></text> </view> </view> // wxss ======================================== .warp{ display: flex; flex-flow: column;} .bg_cl{ width: 100%; flex: 1; height: 400rpx; background: pink;} .bg_cl:nth-child(2),.bg_cl:nth-child(4){ background: purple;} .bottom{ line-height: 50rpx; font-size: 24rpx; display: flex; align-items: center; justify-content: center;} /*過渡動畫 */ .loading{ width: 148rpx; height: 44rpx;} .loading text{ display: inline-block; width: 20rpx; height:20rpx; margin-right: 5px; border-radius: 50%; background:#999; -webkit-animation: load 1.04s ease infinite; } .loading text:last-child{ margin-right: 0px; } @-webkit-keyframes load{ 0%{ opacity: 1; -webkit-transform: scale(1); } 100%{ opacity: 0.2; -webkit-transform: scale(.3); } } .loading text:nth-child(1){ -webkit-animation-delay:0.13s; } .loading text:nth-child(2){ -webkit-animation-delay:0.26s; } .loading text:nth-child(3){ -webkit-animation-delay:0.39s; } .loading text:nth-child(4){ -webkit-animation-delay:0.52s; } .loading text:nth-child(5){ -webkit-animation-delay:0.65s; } //js========================================================= onReachBottom(e){ console.log("底部")// 滾動到頁面執行 該 方法 wx.showToast({ title: '加載中...', icon:'loading', duration:2000 }) /* 這里執行你需要的請求數據追加到循環數組就好了 */ }, onPageScroll(e){ //console.log(e) //滾動條 滾動的位置(e.scrollTop)從頭部開始計算 },

第二種:可以用 scroll-view 組件,scroll-y為true 時允許縱向滾動、使用scroll-view 組件時需要設置固定的高度。組件中有一個bindscrolltolower 觸底 /右邊 方法。詳情見官方文檔(PS: 使用組件會在頁面產生一個滾動條,而page中也會有一個此時會出現問題,可以在頁面 .json配置文件中 設置:"disableScroll":true 頁面整體不能上下滾動 等價於 wxss 中page{overflow:hidden} ;)
<!-- scroll-view --> <scroll-view scroll-y='true' style="height:{{height}}px" bindscroll='scrollt' bindscrolltolower='scrollBottom'> <view class='warp'> <view wx:for="{{arr}}" class='bg_cl'></view> </view> </scroll-view> ==============wxss 延用上方就好了 下方是js'================= onLoad: function () { var that=this wx.getSystemInfo({ success:res=>{ console.log(res) this.setData({ height: res.windowHeight //獲取屏幕高度 賦值給scroll-view }) } }) }, //scroll- view 滾動條 距頂部多少px scrollt(e){ console.log(e.detail) }, // scroll-view 滾動到底部觸發 scrollBottom(e){ console.log(" 我是scroll 的底部") //此處添加你的 請求方法就好了 這里不多做贅述了。 }
.