之前用jquery时我们可以使用:
$(".classify").eq(0).addClass("addStyleMi").siblings().removeClass("addStyleMi");
动态的为元素切换类名,添加css样式。
但是微信小程序中不提供操作Dom的方法,但我们也可以实现为元素动态切换类名。
效果图:
图1 图2
重点是这句代码
下面是完整的代码:
js:
data: {
// --------二级分类---------
first_names:[
{
"id":1,
"goods_name":"食品土特产"
},
{
"id":2,
"goods_name": "健康器械"
},
{
"id":3,
"goods_name": "营养保健"
},
{
"id": 4,
"goods_name": "健康调理"
},
{
"id": 5,
"goods_name": "保护眼睛"
},
{
"id": 6,
"goods_name": "骨骼健康"
},
{
"id": 7,
"goods_name": "滋补养生"
},
{
"id": 8,
"goods_name": "增强免疫"
},
{
"id": 9,
"goods_name": "国内旅游"
},
],
first_id:0,//用于判断是否是当前选中的
},
// -------动态切换class---------
menuClick: function (e) {
var that = this;
var index = e.currentTarget.dataset.index;//获取当前点击的元素下标
console.log(index);
that.setData({
first_id: index
})
},
wxml:(scroll-view用于滑动)
<view class='moreBoxs'>
<scroll-view class="navContent" scroll-x>
<view class="classify {{first_id==index?'addStyleMi':''}}" bindtap="menuClick" wx:for='{{first_names}}' wx:key='{{index}}' wx:for-item="first_names" wx:for-index="index" data-postid='{{first_names.id}}' data-index='{{index}}' data-postname='{{first_names.goods_name}}'>
<text>{{first_names.goods_name}}</text>
</view>
</scroll-view>
</view>
wxss:
/* 分类开始 */
.moreBoxs{
width: 100%;
height: 102rpx;
border-bottom: solid 2rpx #e5e5e5;
position: fixed;
top: 0;
background-color: #ffffff;
z-index: 500;
}
.navContent{
width: 100%;
height: 102rpx;
white-space: nowrap;
}
.classify {
height: 102rpx;
/*width: 8%;*/
margin-left: 42rpx;
line-height: 102rpx;
text-align: center;
font-size: 28rpx;
display: inline-block;
}
.addStyleMi {
height: 96rpx;
border-bottom: solid 6rpx #eb3737;
font-weight: bold;
color: #eb3737;
font-size: 28rpx;
}
/* ---------隐藏滚动条 */
::-webkit-scrollbar {
width: 0;
height: 0;
color: transparent;
}