uniapp
效果是模拟发送聊天信息,需要scrollview在收到新消息时滚动到底部最新的位置
项目是vue2的,代码如下
// 第一种 高度固定值
scrollToBottom(selector) {this.$nextTick(() => {const dom = uni.createSelectorQuery().in(this).select(selector)dom.scrollOffset(({scrollHeight}) => {// 这个this.scrollTop 是data中的变量 控制srcollView的滚动距离 500为滚动元素的高度this.scrollTop = scrollHeight - 500}).exec()})
}// 第二种 高度动态获取
// 不建议这种写法 !!!
// 嵌套获取可以获取到元素的实际高度 避免固定的数值 但是由于嵌套操作dom存在严重的性能问题
// 可以通过boundingClientRect先获取到后存储为变量,再scrollOffset进行使用来解决
scrollToBottom(selector) {this.$nextTick(() => {const dom = uni.createSelectorQuery().in(this).select(selector)dom.boundingClientRect(({height}) => {dom.scrollOffset(({scrollHeight}) => {// 这个this.scrollTop 是data中的变量 控制srcollView的滚动距离 this.scrollTop = scrollHeight - height}).exec()}).exec()})
}
使用时直接传入scrollview
的选择器即可
使用示例
<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y charRecord"><!-- 聊天信息 -->
</scroll-view>
onFetchMessage(){// 接收到信息 放入列表this.scrollToBottom('.charRecord') // .charRecord 是 scroll-view 的类名
}
如果恰好你需要隐藏scrollview的滚动条,那就可以加上这个代码
在App.vue
中添加
<style lang="scss">/*每个页面公共css */scroll-view ::-webkit-scrollbar {display: none !important;width: 0 !important;height: 0 !important;-webkit-appearance: none;background: transparent;}::-webkit-scrollbar {display: none;}
</style>