微信小程序button選中改樣式-實現單選/多選


小程序實現多button單選/多選

紅色為選中狀態

單選

多選

①wxss

/* pages/button-select/button-select.wxss */

.button_container{
  display: flex;
  flex-direction: row;
  justify-content: space-around
}
/* 按鈕未選中 */
.normal_button{
  background: greenyellow
}
/* 按鈕選中 */
.checked_button{
  background: red;
  color: white
  
}

②wxm

樣式選中改變是通過三元運算符實現的

<!--pages/button-select/button-select.wxml-->
<view class='button_container'>
  <block wx:for="{{buttons}}" wx:key="buttons">
  <button class='{{item.checked?"checked_button":"normal_button"}}' data-id='{{item.id}}' bindtap='radioButtonTap'>{{item.name}}</button>
  </block>
</view>
<text>{{msg}}</text>

③js

Page({...})中填充按鈕數據

data: {
    buttons: [{ id: 1, name: '銀色' }, { id: 2, name: '白色' }, { id: 3, name: '黑色' }],
    msg:'',
  },

默認使第一個按鈕被選中Page({...})

onLoad: function (options) {
    this.data.buttons[0].checked = true;
    this.setData({
      buttons: this.data.buttons,
    })
  },

Page({...})中添加事件監聽方法(單選)

/**
 * 事件監聽,實現單選效果
 * e是獲取e.currentTarget.dataset.id所以是必備的,跟前端的data-id獲取的方式差不多
 */
radioButtonTap: function (e) {
    console.log(e)
    let id = e.currentTarget.dataset.id
    console.log(id)
    for (let i = 0; i < this.data.buttons.length; i++) {
      if (this.data.buttons[i].id == id) {
        //當前點擊的位置為true即選中
        this.data.buttons[i].checked = true;
      }
      else {
        //其他的位置為false
        this.data.buttons[i].checked = false;
      }
    }
    this.setData({
      buttons: this.data.buttons,
      msg: "id:"+id
    })
  },

Page({...})中添加事件監聽方法(多選)

記得在wxml中修改綁定方法bindtap='radioButtonTap'

  checkButtonTap:function(e){
    console.log(e)
    let id = e.currentTarget.dataset.id
    console.log(id)
    for (let i = 0; i < this.data.buttons.length; i++) {
      if (this.data.buttons[i].id == id) {
        if (this.data.buttons[i].checked == true) {
          this.data.buttons[i].checked = false;
         
        } else {
          this.data.buttons[i].checked = true;
          
        }
      }
    }
   this.setData({
     buttons: this.data.buttons,
     msg: "id:"+id
    })
    
  },


免責聲明!

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



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