微信小程序 動態更改選中對象的css樣式


邏輯

①給原數據添加選中狀態,例如:select:false 和 判斷依據:例如 id:1

②wxml頁面三目判斷例如: class=" {{ xx.select? 'select' : 'defult' }}"

③在wxss頁面分別創建select 和 defult 樣式

④給對應標簽添加事件接受傳入的id值,並進行判斷,將點擊id的select設置為true,其他為false

 

案例

JS

 1 Page({
 2 
 3   /**
 4    * 頁面的初始數據
 5    */
 6   data: {
 7     monster: {//假設原數據
 8       '帕里鎮': {
 9         '獨眼蝙蝠': {
10           'id': 1,
11           'name': '獨眼蝙蝠',
12           'select': false,
13         },
14         '彭哆菇': {
15           'id': 2,
16           'name': '彭哆菇',
17           'select': false,
18         },
19         '象牙甲蟲': {
20           'id': 3,
21           'name': '象牙甲蟲',
22           'select': false,
23         },
24 
25       },
26       '晨光鎮': {
27         '魔導戰甲': {
28           'id': 4,
29           'name': '魔導戰甲',
30           'select': false,
31         },
32         '邪惡的南瓜': {
33           'id': 5,
34           'name': '邪惡的南瓜',
35           'select': false,
36         },
37         '巨劍浪人': {
38           'id': 6,
39           'name': '巨劍浪人',
40           'select': false,
41         },
42       }
43     }
44   },
45   
46   /**
47    * 當選中時觸發
48    * @param {*} e 
49    */
50   OnSelect(e) {
51     let { id } = e.currentTarget.dataset
52     let { monster } = this.data
53 
54     console.log("當前點擊:", id)
55 
56     //根據id,將當前選中的id的select設置為true
57     for (let i in monster) {
58       for (let o in monster[i]) {
59         if (monster[i][o].id == id) {
60           monster[i][o].select = true
61         } else {
62           monster[i][o].select = false
63         }
64       }
65     }
66 
67     //渲染數據
68     this.setData({
69       monster
70     })
71 
72   },
73 })

WXML

 1 <view class="box">
 2 
 3   <view class="monster_box" wx:for="{{monster}}" wx:for-item="item" wx:for-index="index" wx:key="index">
 4 
 5     <view wx:for="{{item}}" wx:for-item="item2" wx:for-index="index2" wx:key="index2">
 6       <!-- 
 7         class="{{item2.select? 'select':'defult'}}"
 8         三目運算,有item2.select嗎?(為true時) 觸發左側樣式:否則觸發右側樣式 
 9 
10         傳值:data-id="{{item2.id}} 綁定事件:bindtap="OnSelect" 接收傳入的值
11       -->
12       <view class="{{item2.select? 'select':'defult'}}" data-id="{{item2.id}}" bindtap="OnSelect">{{item2.name}}</view>
13 
14     </view>
15 
16   </view>
17 
18 </view>

WXSS

 1 .monster_box{
 2   display: flex;
 3   text-align: center;
 4   margin: 20rpx;
 5 }
 6 .select{
 7   width: 200rpx;
 8   border-bottom: 5rpx solid rgb(255, 124, 124);
 9   margin: 20rpx;
10 }
11 .defult{
12   width: 200rpx;
13   margin: 20rpx;
14 }

效果圖

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM