效果图:
WXML文件
<view class="tab">
<scroll-view class="nav" scroll-x="true" scroll-left="{{scrollLeft}}">
<block wx:for="{{allTitle}}" wx:for-index="idx" wx:key="idex">
<view class="nav-item {{currentIndex==idx ? 'active' : ''}}" data-current="{{idx}}" bindtap="changeTitle">{{item.title}}</view>
</block>
</scroll-view>
<swiper class="content-container" current="{{currentIndex}}" circular="{{false}}" bindchange="changeContent">
<swiper-item class="content">客厅</swiper-item>
<swiper-item class="content">厨房</swiper-item>
<swiper-item class="content">卧室</swiper-item>
<swiper-item class="content">KTV</swiper-item>
<swiper-item class="content">浴室</swiper-item>
<swiper-item class="content">广场</swiper-item>
<swiper-item class="content">公园</swiper-item>
<swiper-item class="content">博物馆</swiper-item>
</swiper>
</view>
JS文件
//index.js
//获取应用实例
const app = getApp()
Page({
data: {
allTitle:[
{ id: 0, title: '客厅'},
{ id: 1, title: '厨房'},
{ id: 2, title: '卧室'},
{ id: 3, title: 'KTV'},
{ id: 4, title: '浴室'},
{ id: 5, title: '广场'},
{ id: 6, title: '公园'},
{ id: 7, title: '博物馆'}
],
currentIndex: 0, //当前选中标题的下标
scrollLeft: 0, //tab滚动条的位置
},
onLoad: function () {
},
//点击切换标题
changeTitle(event){
let index = event.target.dataset.current;//当前点击标题的index
this.setData({
currentIndex:index
})
},
//滑动切换内容
changeContent(event){
let current = event.detail.current;
let singleNavWidth = wx.getSystemInfoSync().windowWidth / 5;
this.setData({
currentIndex: current,
scrollLeft: (current - 2) * singleNavWidth
});
}
})
WXSS文件
page{
width: 100%;
height: 100%;
}
.tab {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
.nav {
height: 80rpx;
width: 100%;
overflow: hidden;
white-space: nowrap;
line-height: 80rpx;
font-size: 16px;
position: fixed;
top: 0;
left: 0;
z-index: 99;
}
.nav-item {
width: 20%;
display: inline-block;
text-align: center;
}
.active {
color: #FF6471;
position: relative;
}
.active:after{
content: "";
display: block;
width:100%;
height: 5rpx;
border-radius: 8rpx;
background: #FF6471;
position: absolute;
bottom: 0;
}
.content-container {
padding-top: 180rpx;
height: 100%;
width: 100%;
text-align: center;
}
.content{
margin-top:180rpx;
}
/* 隐藏滚动条 */
::-webkit-scrollbar {
width: 0;
height: 0;
color: transparent;
}