最近想做个商城类的小程序,特意研究了下顶部的Tab分类实现,在网上找了好多资料和实现,没有特别满意的,于是找了一个在其中的基础上进行了优化和修改,特此记录下
先看效果:
上代码:
scolltab.wxml
<!--pages/scolltab/scolltab.wxml-->
<scroll-view scroll-x class='swiper-nav' scroll-left='{{swiperNav.x}}' scroll-with-animation='true' bindtap='swiperNavTap'>
<text wx:for='{{swiperNav.arr}}' wx:key='index' class='item-nav {{swiperNav.i==index ? "active" : ""}}' data-i='{{index}}'>{{item.txt}}</text>
</scroll-view>
scolltab.js:
// pages/scolltab/scolltab.js
Page({
/**
* 页面的初始数据
*/
data: {
swiperNav: {
i: 0,
arr: [
{ v: 0, txt: "推荐" },
{ v: 1, txt: "生鲜" },
{ v: 2, txt: "女装" },
{ v: 3, txt: "进口" },
{ v: 4, txt: "饮料" },
{ v: 5, txt: "零食" },
{ v: 6, txt: "生鲜" },
{ v: 7, txt: "女装" },
{ v: 0, txt: "推荐" },
{ v: 1, txt: "生鲜" },
{ v: 2, txt: "女装" },
{ v: 3, txt: "进口" },
{ v: 4, txt: "饮料" },
{ v: 5, txt: "零食" },
{ v: 6, txt: "生鲜" },
{ v: 7, txt: "女装" },
{ v: 8, txt: "速食" }
]
}
},
swiperNavTap: function (e) {
console.log(e);
/*获取可视窗口宽度*/
var w = wx.getSystemInfoSync().windowWidth;
var leng = this.data.swiperNav.arr.length;
var i = e.target.dataset.i;
var disX = (i - 2) * w / leng;
if (i != this.data.swiperNav.i) {
this.setData({
'swiperNav.i': i
})
}
this.setData({
'swiperNav.x': (i-1)*44
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
}
})
scolltab.wxss:
/* pages/scolltab/scolltab.wxss */
/*横向导航*/
.swiper-nav{
background-color: #fff;
white-space: nowrap;
-webkit-tap-highlight-color:rgba(0,0,0,0);
}
.swiper-nav .item-nav{
position: relative;
padding: 30rpx 22rpx;
color: #5C5C5C;
font-size: 32rpx;
cursor: pointer;
display: inline-block;
font-weight: 550;
}
.swiper-nav .active{color: #f43838}
.swiper-nav .active::after{
content:'';
position: absolute;
left: 22rpx;
right: 22rpx;
height:0;
border-bottom: 8rpx solid #f43838;
border-radius: 2rpx;
bottom: 18rpx
}
scroll.json:
{
"usingComponents": {}
}
OK 直接可运行