让微信小程序scroll-view的滚动条想滚那里滚那里

2,531 阅读2分钟

「这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战

背景是这样的,微信小程序有一个tab切换页面,tab切换页面有两个内容框,我是使用scroll-view进行制作,然后在切换tab页面时,相应的scroll-view里的滚动条需要置顶处理

我们可以看到官方文档描述scroll-view里有一个scroll-into-view属性,该属性的描述如下

scroll-into-view的值应为某子元素id(id不能以数字开头)。设置哪个方向可滚动,则在哪个方向滚动到该元素

那么我们可以在这个属性里大作文章,只要在scroll-view里放置一个id值为设置的一个自定义值就可以实现切换tab时,对应的内容框滚动条都自动滚到顶部,如下面代码所示,下面代码是我使用Taro小程序框架演示的,原生的也同理

import Taro from '@tarojs/taro'
import { View } from '@tarojs/components'
import { AtTabs, AtTabsPane } from 'taro-ui'
export default class Index extends Taro.Component {
  constructor () {
    super(...arguments)
    this.state = {
      current: 0,
    }
  }
  handleClick (value) {
    this.setState({
      current: value
    })
  }
  render () {
    const tabList = [{ title: '标签第一页' }, { title: '标签第二页' }, { title: '标签第三页' }]
    return (
      <AtTabs current={this.state.current} tabList={tabList} onClick={this.handleClick.bind(this)}>
        <AtTabsPane current={this.state.current} index={0} >
          <ScrollView scrollY scrollIntoView='content-0'>
          <View id='content-0'></View>
          标签页一的内容
          </ScrollView>
        </AtTabsPane>
        <AtTabsPane current={this.state.current} index={1} >
          <ScrollView scrollY scrollIntoView='content-1'>
          <View id='content-1'></View>
          标签页二的内容
          </ScrollView>
        </AtTabsPane>
        <AtTabsPane current={this.state.current} index={2} >
          <ScrollView scrollY scrollIntoView='content-2'>
          <View id='content-2'></View>
          标签页三的内容
          </ScrollView>
        </AtTabsPane>
      </AtTabs>
    )
  }
}

如第一个tabscroll-view里放置一个id值为content-0view,那么在切换tab页时,scroll-view会根据我们设置的scroll-into-view属性定位到子元素的id上,到达滚动条自动置顶的效果

<AtTabsPane current={this.state.current} index={0} >
  <ScrollView scrollY scrollIntoView='content-0'>
    <View id='content-0'></View>
    标签页一的内容
  </ScrollView>
</AtTabsPane>

同理的,假如需要滚动条滚到最低下,把相应的子元素id放到最低下即可,例如某些聊天界面,需要定位到最新那条

<AtTabsPane current={this.state.current} index={0} >
  <ScrollView scrollY scrollIntoView='content-0'>
    标签页一的内容
    <View id='content-0'></View>
  </ScrollView>
</AtTabsPane>

结语

以上是我使用scroll-view的一点小心得,原创不容易,希望能对大家有帮助~你的赞对我来说很重要,希望能获得你的赞👍~大家也可以多在评论区交流讨论哦,谢谢啦~

更多文章推荐:

「不再迷茫!看了这篇文章让你上手Vue3.0开发有丝滑般体验」

「看一眼,Vue3 script-setup语法糖下组件通信就学会了(附源码)」

「超详细!监听微信小程序五种切后台情况」

「三分钟学会使用requestAnimationFrame实现倒计时」