目标需求:实现下图,给点击的view增加类,每次只能选择一个。
主要思路:给点击的view增加类,依靠点击的index对state进行赋值。如果相同时,给该view增加类。
效果演示:
wxml
<view class="iconusecont-div {{state==index?'active-tag':''}}" bindtap="select_use" wx:for="{{use}}" data-key='{{index}}'> <view class="flex-item"> <rich-text class='use_name'>{{item.use_name}}</rich-text> </view> </view>
wxss
/* 用途 */ .iconusecont-div { display: inline-block; width: 32%; text-align: center; margin-top: 30rpx; } .flex-item { display: inline-block; width: 173rpx; height: 78rpx; font-size: 26rpx; border: 2rpx solid #999; text-align: center; border-radius: 10rpx; color: #000; cursor: pointer; line-height: 30rpx; } .use_name { font-size: 34rpx; line-height: 79rpx; } .active-tag .flex-item { background: #03e2ff; color: #fff; border: 1rpx solid #fff; }
js
Page({ data: { use: [{ "use_name": "全部" }, { "use_name": "经济实惠型" }, { "use_name": "家用学习型" }, { "use_name": "豪华发烧型" }, { "use_name": "疯狂游戏型" }, { "use_name": "商务办公型" }, { "use_name": "经济实惠型" }, { "use_name": "家用学习型" }, ], state: '', }, //选择用途后加样式 select_use: function(e) { this.setData({ state: e.currentTarget.dataset.key, }); }, onReady: function() {}, })