html
<view class="main">
<view class="tab">
<view wx:for="{{tabList}}" bindtap="clickTab" data-hash="{{item.hash}}" data-id="{{item.id}}" class="tab_item {{tabIndex == item.id ? 'active': ''}}" wx:key="id">
{{item.name}}
</view>
<view class="tab_line" style="transform: translateX({{translateX}}px) translateX(-50%)"></view>
</view>
</view>
js
Page({
/**
* 页面的初始数据
*/
data: {
tabIndex: 0,
translateX: 0,
// 是否显示底部tab
isShowTab: true,
tabList: [{
id: 0,
hash: 'service',
name: '服务介绍'
}, {
id: 1,
hash: 'case',
name: '真实案例'
}, {
id: 2,
hash: 'comment',
name: '用户评价'
}],
isShowHeadTab: true
},
/**
* 组件的方法列表
*/
clickTab: function(e) {
this.handleLocation(e.currentTarget.dataset['id'])
},
// 处理定位 根据索引设置定位栏
handleLocation: function(index) {
let vm = this
// 屏幕宽度
let x = wx.getSystemInfoSync().windowWidth
// 每个宽度
let lenWidth = x / (vm.data.tabList || []).length
// 平移距离
this.setData({
tabIndex: index,
translateX: ((lenWidth) / 2 + (lenWidth * index))
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function(options) {
this.handleLocation(0)
},
})
css
.tab {
display: flex;
100%;
height: 94rpx;
background: #fff;
position: relative;
z-index: 1;
top: 0;
box-shadow: 0rpx 2rpx 8rpx 0rpx rgba(204, 204, 204, 0.3);
}
.tab .tab_item {
display: flex;
align-items: center;
flex: 1;
justify-content: center;
font-size: 26rpx;
color: #999;
height: 94rpx;
}
.tab .tab_item.active {
color: #f8444b;
font-weight: 550;
}
.tab .tab_line {
position: absolute;
left: 0;
bottom: -5rpx;
65rpx;
height: 6rpx;
background-color: #f8444b;
border-radius: 3rpx;
transition-duration: 0.3s;
}