设置 scroll-view
<scroll-view :scroll-y="true" :scroll-with-animation="true" :scroll-top="scrollTop" :style="`height:${height}px`">
<view v-for="item in 10" :id="`box${item}`">box {{item}}</view>
</scroll-view>
scroll-y:设置为纵向
scroll-with-animation:在设置滚动条位置时使用动画过渡
scroll-top:设置竖向滚动条位置
如果是纵向一定要设置高度,不然不生效
scroll-view:scroll-view | uni-app官网
通过onLoad获取界面高度
const scrollTop = ref(0)
const height = ref(0)
onLoad(() => {
height.value = uni.getSystemInfoSync().windowHeight
})
通过onReady + nextTick 设置scrollTop
onReady(() => {
nextTick(() => {
const dom = uni.createSelectorQuery()
dom.select(`#box9`)
.boundingClientRect((e: any) => {
scrollTop.value = e.top
}).exec()
})
})
这里没有设置 in,有需要可以在in中设置选取范围,官方文档:uni.createSelectorQuery() | uni-app官网
将选择器的选取范围更改为自定义组件
component
内,返回一个SelectorQuery
对象实例。(初始时,选择器仅选取页面范围的节点,不会选取任何自定义组件中的节点)。