0


【uniapp】scroll-view 实现自动滚动到最底部

在做uniapp项目中,有个滚动视图组件

scroll-view

,跟微信小程序里的组件一样的,想要实现自动滚动到最底部,是一件容易忽略的,小事情。

文章目录

问题呈现

官网uniapp文档上说可以控制滚动条,并没有自动滚动到底部的设置选项,请看布局源代码,如下,大多数可能都是这样写的

<template><view><scroll-viewclass="scroll-view":style="{height:scrollViewHeight+'px'}":scroll-y="true":scroll-top="scrollTop":scroll-with-animation="true"><blockv-for="(item,index) in images":key="index"><imageclass="item":src="item.src"mode="aspectFill"></image></block></scroll-view></view></template><script>exportdefault{data(){return{images:[],scrollTop:0,//滚动条位置scrollViewHeight:300,//滚动视图的高度//...};},//...}</script>

🤔 虽然可以控制滚动条位置,但是,不知道滚动视图框内的内容高度,要怎么精准控制滚动条位置呢

解决方案

通过各种尝试,认为最好的方案就是,在滚动视图组件内再加一层

view

视图,布局改动后,源代码如下

<template><view><scroll-viewclass="scroll-view":style="{height:scrollViewHeight+'px'}":scroll-y="true":scroll-top="scrollTop":scroll-with-animation="true"><viewid="scroll-view-content"><blockv-for="(item,index) in images":key="index"><imageclass="item":src="item.src"mode="aspectFill"></image></block></view></scroll-view></view></template><script>//此处省略...</script>

还有,实现滚动底部的处理方法

scrollToBottom()

,代码如下

exportdefault{data(){return{images:[],scrollTop:0,//滚动条位置scrollViewHeight:300,//滚动视图的高度//...};},mounted(){let i =10;do{this.images.push({src:'../../static/test.jpg',//...});
            i--;}while(i>0);},//...methods:{scrollToBottom(){this.$nextTick(()=>{
                uni.createSelectorQuery().in(this).select('#scroll-view-content').boundingClientRect((res)=>{let top = res.height-this.scrollViewHeight;if(top>0){this.scrollTop=top;}}).exec()})}}}

注意事项

需要注意组件

scroll-view

的属性设置

  • 需要设置固定高度,这样视图里面内容当只有超过该高度才会有滚动效果
  • 需要设置scroll-with-animation=true,可以出现慢慢滚动到底部效果

在这里插入图片描述

标签: 前端 javascript

本文转载自: https://blog.csdn.net/zs1028/article/details/127882509
版权归原作者 TA远方 所有, 如有侵权,请联系我们删除。

“【uniapp】scroll-view 实现自动滚动到最底部”的评论:

还没有评论