这篇文章主要介绍“小程序中如何让scroll-view按照指定位置滚动”,在日常操作中,相信很多人在小程序中如何让scroll-view按照指定位置滚动问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”小程序中如何让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>
)
}
}
如第一个tab
的scroll-view
里放置一个id值为content-0
的view
,那么在切换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按照指定位置滚动”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。