浅析小程序中怎么让scroll-view按照指定位置滚动

 2099

本篇文章给大家介绍一下在微信小程序中怎么让scroll-view按照指定位置滚动,无需在写额外的js脚本,就可获得极佳的体验,希望对大家有所帮助!


浅析小程序中怎么让scroll-view按照指定位置滚动


背景是这样的,微信小程序有一个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>


本文转载于:掘金社区,如有侵犯,请联系删除


本文网址:https://www.zztuku.com/detail-9891.html
站长图库 - 浅析小程序中怎么让scroll-view按照指定位置滚动
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐

    AI打造漂亮文字效果