前言:
大概有兩種方式,一種是使用 uni.pageScrollTo 方法;
另一種是使用 scroll-view 標簽的屬性:scroll-top(距離值 num) 或 scroll-into-view(子元素的id,不能以數字開頭 string);
兩種方式的前提是:提供具體的高度值(scroll-view 也可以橫向滾動到指定位置)。
一、uni.pageScrollTo
uni.pageScrollTo 不起效果的原因可能有兩: 1,值格式不對;2,布局格式不對。
如果是傳入 selector 不起效:
uni.pageScrollTo({ duration: 300, selector: id // string 選擇器 });
應該是 id 格式不支持純數字,其實類名之類的最好不要用數字,實在要用,使用單詞加數字后綴。
如果傳入 scrollTop 不起效:
uni.pageScrollTo({ duration: 300, scrollTop: top // number number number! });
那么應該是布局的問題, 它是頁面級的滾動:所有的 滾動單元 必須是在根元素下,由 滾動單元 直接撐起來的高度,就可以滾動到指定位置。
不能內嵌到深層里面去,我布局比較喜歡來一個 container ,然后包含 title、content、 pop...之類的,滾動內容全在 content 里面,這樣子是不起效果的,滾不動,需要是 container 的子元素。
官網的截圖,可能是改了值類型沒更新:

完整的方法:
uni.createSelectorQuery().select(".cci-end").boundingClientRect((res)=>{
console.log(res)
const scrollH = res.top;
uni.pageScrollTo({
duration: 100,// 過渡時間
scrollTop: scrollH,// 滾動的實際距離
})
}).exec()
二、scroll-view 標簽
<scroll-view class="container-chat-items" scroll-y :scroll-top='scrollTop' :style="{height: msgHeight + 'px'}">
</scroll-view>
使用這個沒發現啥問題,直接隨時修改 scrollTop 的值就可以滾動,在需要使用 scroll-view 的地方直接用。
最后:
獲取元素的信息都是使用
uni.createSelectorQuery().select(".cci-end").boundingClientRect((res)=>{
console.log(res)
}).exec()
注: 需要在生命周期 mounted 后進行調用。
建議可以在需要的位置使用一個 高度 0 的標簽標記 ID 來定位。
自定義組件編譯模式(默認模式),需要使用到 selectorQuery.in 方法,包裝下:
Vue.prototype.$getRect = function(selector) {
return new Promise(resolve => {
uni.createSelectorQuery()
.in(this)['select'](selector)
.boundingClientRect(rect => {
if (rect) {
resolve(rect);
} else {
resolve('no info');
}
})
.exec();
});
}
