最近在作即時聊天時,碰到了自動滑動到底部的問題,2個解決方式(其中方法1有瑕疵):函數
方法一:this
// 獲取容器高度,使頁面滾動到容器底部 pageScrollToBottom: function() { wx.createSelectorQuery().select('#page').boundingClientRect(function(rect) { if (rect){ // 使頁面滾動到底部 console.log(rect.height); wx.pageScrollTo({ scrollTop: rect.height }) } }).exec() },
將js方法在頁面加載完成以及發送完消息後執行,便可自動滾動到頁面底部,在須要滾動的view上使id="page";不過問題有二:.net
一、頁面在自動上滑時會出現抖動現象,給人感受很不舒服;code
二、及時聊天在頁面下方會有一個input輸入框,若是該input使用confirm-hold="true"(點擊右下角保持鍵盤不收起),那麼在用該方法上滑時會將input的光標帶到上面去,致使光標位置偏移。xml
方法二:使用scroll-view組件htm
wxml——生命週期
<scroll-view id="page" style='height: {{windowHeight - 60}}px' scroll-y="true" scroll-top="{{scrollTop}}"> //滾動部分代碼 </scroll-view>
ps:頁面中的60,是本身輸入框的高度get
js——input
data: { scrollTop: 0,//控制上滑距離 windowHeight: 0,//頁面高度 } /** * 生命週期函數--監聽頁面初次渲染完成 */ onReady: function() { var height = wx.getSystemInfoSync().windowHeight; this.setData({ windowHeight: height }) this.pageScrollToBottom(); }, // 獲取容器高度,使頁面滾動到容器底部 pageScrollToBottom: function() { var that = this; var height = wx.getSystemInfoSync().windowHeight; wx.createSelectorQuery().select('#page').boundingClientRect(function(rect) { if (rect){ that.setData({ windowHeight: height, scrollTop: rect.height }) } }).exec() },
一樣的,將js方法在頁面加載完成以及發送完消息後執行,便可自動滾動到頁面底部,自測可行;io
方法二參考自:https://www.jb51.net/article/150492.htm