先看一下效果展示:
主要用到 scroll-view 组件 scroll-into-view 属性;当点击导航菜单的时候,我们改变相应的 scroll-into-view 的值,并且同时需要在 scroll-view 组件内相应位置处的子元素上定义相应的 id;因为scroll-into-view 值应为某子元素 id,设置哪个方向可滚动,则在哪个方向滚动到该元素。
.wxml代码
<!--index.wxml-->
<view style="height:auto">
<scroll-view class="tab-list" scroll-x="{{true}}" enable-flex='{{true}}'>
<block wx:for='{{tabList}}' wx:key='tab'>
<view class='tab-item' bindtap='onTabClick' data-index="{{index}}">
<text class="tab-title{{tabIndex == index?' select':''}}">{{item.title}}</text>
</view>
</block>
</scroll-view>
</view>
<view style="height:auto">
<scroll-view style="height:100vh" scroll-y="{{true}}" scroll-into-view="{{tabItem}}" enable-flex="{{true}}"
scroll-with-animation>
<block wx:for="{{tabList}}" wx:key="index">
<view id='tabItem-{{index}}' style="background-color:{{item.bgColor}};height:500rpx;">
{{item.title}}
</view>
</block>
</scroll-view>
</view>
.wxss代码
.tab-list {
width: 100vw;
height: 90rpx;
white-space: nowrap;
box-sizing: border-box;
display: block;
background: #fff;
position: static;
top: 0;
}
.tab-item {
width: 18%;
height: 90rpx;
display: inline-block;
white-space: normal;
box-sizing: border-box;
font-size: 28rpx;
line-height: 90rpx;
text-align: center;
display: inline-block;
}
.tab-title {
width: 100%;
color: #333;
}
.tab-title.select {
color: #00b7de;
}
.js代码
// index.js
let tabList = [{
title: '第一',
bgColor: '#FFFFE0'
},
{
title: '第二',
bgColor: '#C7A698'
},
{
title: '第三',
bgColor: '#00B26A'
},
{
title: '第四',
bgColor: '#0F8BDA'
},
{
title: '第五',
bgColor: '#BEDBE9'
},
{
title: '第六',
bgColor: '#FFCA28'
}
]
Page({
data: {
tabList: tabList,
tabIndex: 0,
tabItem: ''
},
onTabClick(e) {
let curTabIndex = e.currentTarget.dataset.index
this.setData({
tabIndex: curTabIndex,
tabItem: 'tabItem-' + curTabIndex
})
}
})
注意点:
- scroll-into-view 与子元素 id 不能以数字开头;
- scroll-with-animation属性:在设置滚动条位置时使用动画过渡;
- 如果scroll-view占页面整个高度,可设置 scroll-view的高度 height:100vh , 设置height:100%无效
源代码下载地址: https://download.csdn.net/download/ah_biao/16418938.